프로그래밍 언어/Java

[Java]toString 메서드에 대한 이해

benjykim 2018. 9. 11. 21:04
반응형

최근 자바의 정석이란 책을 공부하며 다음과 같은 코드를 만났다.

import java.util.ArrayList;

class Fruit { public String toString() {return "Fruit";} }
class Apple extends Fruit { public String toString() {return "Apple";} }
class Grape extends Fruit { public String toString() {return "Grape";} }
class Toy { public String toString() {return "Toy";} }

public class FruitBoxEx1 {
public static void main(String[] args) {
Box<Fruit> fruitBox = new Box<Fruit>();
Box<Apple> appleBox = new Box<Apple>();
Box<Toy> toyBox = new Box<>();

fruitBox.add(new Fruit());
fruitBox.add(new Apple());

appleBox.add(new Apple());
appleBox.add(new Apple());

toyBox.add(new Toy());

System.out.println(fruitBox);
System.out.println(appleBox);
System.out.println(toyBox);
}
}

class Box<T> {
ArrayList<T> list = new ArrayList<>();
void add(T item) { list.add(item); }
T get(int i) { return list.get(i); }
int size() { return list.size(); }
public String toString() { return list.toString(); }
}

갑자기 "list.toString()" 문장이 어떻게 동작되는지 궁금했다.

사실 여지껏 toString() 함수를 가져다 쓰기만 했을 뿐 어떻게 동작하는 지에 대한 궁금증을 가져본 적이 없었다.


이번 기회에 더 자세히 알고자 했다.


우선 "java ArrayList"를 검색해서 자바 문서로 들어가면 아래와 같은 내용이 나온다.

여기서 'Ctrl + F'를 눌러 'toString'을 검색하면 아래와 같이 나온다. 

Methods inherited from class java.util.AbstractCollection

containsAlltoString

그럼 AbstractCollection을 살펴보자.


toString

public String toString()
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
Overrides:
toString in class Object
Returns:
a string representation of this collection

내용을 읽어보면 대충 다음과 같은 내용이다.

"해당 collection의 string 대표?를 리턴한다. 이 string 대표는 list로 구성되어 있는데 이 list에는 iterator에 의해 리턴된 순서로 collection의 요소들이 있다...(생략)... 요소들은 String.valueOf(Object)에 의해 string으로 변환된다.


우선 iterator를 통해 순차적으로 리스트의 요소들에 접근한다는 것을 알았다. 


그리고 String.valueOf(Object)를 살펴보자.


valueOf

public static String valueOf(Object obj)
Returns the string representation of the Object argument.
Parameters:
obj - an Object.
Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
See Also:
Object.toString()

null이 아닐 경우 obj.toString()의 값이 리턴된다고 써져있다. 다시 Object.toString()을 타고 들어간다.


toString

public String toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
 
Returns:
a string representation of the object.

그럼 결국 조상님(Object)께 도착하게 된다. 



정리를 해보자.

1) list라는 변수가 toString() 함수를 호출하면 어떻게 "[Fruit, Apple]"이 결과로 출력되는지 궁금했다.


2) java doc에서 찾아보니 ArrayList위에는 AbstractCollection 클래스가 있고 이 안에 toString()메소드를 

list가 호출하는 것이었다.


3) list.toString()이 어떻게 동작하냐면, iterator에 의해 list의 요소들이 하나씩 리턴되는데 이 리턴된 오브젝트는 

String.valueOf(Object)를 통해서 string으로 변환된다.


4) 그런데 String.valueOf(Object)를 살펴보니 Object.toString()을 통해 string을 리턴한다.


5) 결국 위의 코드에서 Fruit, Apple 등의 클래스는 toString() 메소드를 오버라이딩했기 때문에 Object.toString()이 호출되는 것이 아니라 오버라이드된 Fruit의 toString() 혹은 Apple()의 toString() 등의 함수가 호출된다.



반응형