item 12 : toString을 항상 재정의하라
1. 모든 하위 클래스에서 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
* ({@code "[]"}). Adjacent elements are separated by the characters
* {@code ", "} (comma and space). Elements are converted to strings as
* by {@link String#valueOf(Object)}.
*
* @return a string representation of this collection
*/
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(' ');
}
}2. toString을 구현 시 반환값의 포맷을 문서화할지 결정하자
포맷을 명시한 예
포맷을 명시하지 않은 예
3. String이 반환한 값에 포함된 정보를 얻어올 수 있는 API를 제공하자.
4. 부가 설명
1) toString()을 재정의하는 이유
toString()을 재정의하는 이유2) 자동 생성된 toString()의 활용
toString()의 활용3) 추상 클래스와 toString()
toString()4) Best Practices
✨ 결론
스터디

Last updated