Object 클래스의 toString 메소드는 객체를 출력하면 자동으로 호출되는
메서드 입니다.
기본적으로는 클래스명.객체명@hashcode
의 문자열 형태로 출력됩니다.
// toString에 아무짓도 안하면 이런 형태로 출력됩니다.
// Code of Object.toString()
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
// ex: bookstore.Book@26f0a63f
HashCode는 객체에서 생성된 숫자입니다. HashTable에서 빠르게 값을 저장, 검색 할 수 있도록
일정한 규칙을 갖고 저장 될 수 있도록 만들어 집니다.HashCode 영문 예시 글
하지만, 우리는 toString을 오버라이드 함으로써, 객체를 문자열로 반환할 수 있는 방법으로써 사용할 수 있습니다.
object를 출력할때 자동으로 호출되기 때문에
System.out.println(Object.toString());
System.out.println(Object);
의 값은 같습니다.
public class Book {
@Override
public String toString() {
return this.category + " " + this.bookName + " "
+ this.bookPrice + " " + this.bookDiscountRate ;
}
}
Book book1 = new Book("IT", "SQLPlus", 50000, 5);
Book book2 = new Book("IT", "Java 2.0", 40000, 3);
Object[] book = {book1, book2};
for(int i=0;i < book.length; i++) {
System.out.println("toString: "+ book[i].toString());
System.out.println("일반: "+ book[i]);
}
toString: IT SQLPlus 50000.0 5.0
일반: IT SQLPlus 50000.0 5.0
toString: IT Java 2.0 40000.0 3.0
일반: IT Java 2.0 40000.0 3.0
public class Book {
// @Override
// public String toString() {
// return this.category + " " + this.bookName + " "
// + this.bookPrice + " " + this.bookDiscountRate ;
// }
}
Book book1 = new Book("IT", "SQLPlus", 50000, 5);
Book book2 = new Book("IT", "Java 2.0", 40000, 3);
Object[] book = {book1, book2};
for(int i=0;i < book.length; i++) {
System.out.println("toString: "+ book[i].toString());
System.out.println("일반: "+ book[i]);
}
toString: bookstore.Book@123a439b
일반: bookstore.Book@123a439b
toString: bookstore.Book@26f0a63f
일반: bookstore.Book@26f0a63f
toString을 Override하지 않아
클래스명.객체명@hashcode
형태로 출력되었습니다.
https://qna.programmers.co.kr/questions/2055/sometype2f92e0f4와-같은-값이-아닌-자바-객체의-데이터를-어떻게-출력할-수-있을까요