7/17
21:00 ~ 24:00
item11,12
우선 책을 보면 대다수의 컬렉션 구현체는 추상 컬렉션 클래스들의 toString()메소드를 상속해 쓴다 고 되어있다. 그럼 흔히 사용하는 HashMap과, HashSet을 확인 해 보자. Enum의 toString() 메소드도 확인해 볼 것이다.
HashMap
HashMap은 AbstractMap을 상속받고있다. 그리고 실제로도 HashMap클래스에는 toString()이 재정의 되어있지 않고, AbstractMap의 toString()을 그대로 사용하고 있음을 확인 할 수 있다.
그리고 여러 Map의 구현체, WeakHashMap, TreeMap, LinkedHashMap, EnumMap 들도 AbstractMap의 toString()을 사용하고 있다.
AbstractMap의 toString()은 다음과 같다.
public String toString() {
Iterator<Entry<K,V>> i = entrySet().iterator();
if (! i.hasNext())
return "{}";
StringBuilder sb = new StringBuilder();
sb.append('{');
for (;;) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
sb.append(key == this ? "(this Map)" : key);
sb.append('=');
sb.append(value == this ? "(this Map)" : value);
if (! i.hasNext())
return sb.append('}').toString();
sb.append(',').append(' ');
}
}
HashSet
HashSet은 AbstractSet을 상속받고 있다. 그리고 AbstractSet은 AbstractCollection을 상속받고 있다. 그래서 이 AbstractCollection의 toString()메소드를 사용하게 된다.
AbstractCollection의 toString()메소드는 다음과 같다.
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
HashSet, LinkedHashSet, TreeSet등을 확인 해보자.
toString()을 출력해보면 Set도 익숙한 형태로 보여진다.
Enum
java.lang패키지에 있는 Enum클래스의 toString()은 다음과 같다.
/**
* Returns the name of this enum constant, as contained in the
* declaration. This method may be overridden, though it typically
* isn't necessary or desirable. An enum type should override this
* method when a more "programmer-friendly" string form exists.
*
* @return the name of this enum constant
*/
public String toString() {
return name;
}
단순히 name을 반환하고 있다. 문서 주석을 보면 잘 재정의 하지는 않지만, programmer-friendly한 string이 있는 경우 재정의된다.고 되어있다. 이번 item12와 연결지어 간결하면서 사람이 읽기 쉬운 형태의 유익한 정보의 형태가 바로 programmer-freindly 정도로 이해할 수 있을 것이다.