강의 자료
실습 코드
java.lang 패키지
모든 클래스는 Object 클래스를 상속받는다
toString() 메서드
객체의 정보를 String으로 바꾸어서 사용할 때 쓰임
String이나 Integer 클래스는 이미 재정의되어 있음
toString()메서드 재정의 예
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}
public class BookTest {
public static void main(String[] args) {
Book book = new Book("데미안", "헤르만 헤세");
System.out.println(book);
String str = new String("test");
System.out.println(str); //toString()이 이미 재정의되어 있기 때문에 문자열이 출력됨(==str.toString())
}
}

toString()을 재정의하지 않아 가상 메모리 주소가 출력됨
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public String toString() { //제목과 저자가 나오도록 재정의
return title + ", " + author ;
}
}
public class BookTest {
public static void main(String[] args) {
Book book = new Book("데미안", "헤르만 헤세");
System.out.println(book);
String str = new String("test");
System.out.println(str); //toString()이 이미 재정의되어 있기 때문에 문자열이 출력됨(==str.toString())
}
}

toString()을 재정의하여 제목과 저자가 출력됨
equals() 메서드
두 인스턴스의 주소 값을 비교하여 true/false를 반환
재정의하여 두 인스턴스가 논리적으로 동일함의 여부를 구현함
인스턴스가 다르더라도 논리적으로 동일한 경우 true를 반환하도록 재정의할 수 있음
(같은 학번, 같은 사번, 같은 아이디의 회원...)
hashCode() 메서드
hashCode()는 인스턴스의 저장 주소를 반환함
힙메모리에 인스턴스가 저장되는 방식이 hash 방식
hash : 정보를 저장, 검색하는 자료구조
자료의 특정 값(키 값)에 대한 저장 위치를 반환해주는 해시 함수를 사용

두 인스턴스가 같다는 것은?
논리적으로 동일함을 위해 equals() 메서드를 재정의했다면, hashCode()메서드도 재정의하여 동일한 hashCode 값이 반환되도록 한다
public class Student {
private int studentNum;
private String studentName;
public Student(int studentNum, String studentName) {
this.studentNum = studentNum;
this.studentName = studentName;
}
public String toString() {
return studentNum + ", " + studentName;
}
}
public class EqualsTest {
public static void main(String[] args) {
Student std1 = new Student(100, "Lee");
Student std2 = new Student(100, "Lee");
Student std3 = std1;
System.out.println(std1 == std2); //다른 주소 값이므로 false 반환
System.out.println(std1.equals(std2));
System.out.println(std1 == std3); //같은 주소 값이므로 true 반환
}
}

equals()를 재정의하지 않아 논리적으로 같더라도 주소 값이 다르면 false를 반환
public class Student {
private int studentNum;
private String studentName;
public Student(int studentNum, String studentName) {
this.studentNum = studentNum;
this.studentName = studentName;
}
public String toString() {
return studentNum + ", " + studentName;
}
@Override
public boolean equals(Object obj) { //equals()와 hashCode()를 함께 재정의
if (obj instanceof Student) {
Student std = (Student)obj;
if (this.studentNum == std.studentNum) {
return true;
}
else return false;
}
return false;
}
@Override
public int hashCode() {
return studentNum;
}
}
public class EqualsTest {
public static void main(String[] args) {
Student std1 = new Student(100, "Lee");
Student std2 = new Student(100, "Lee");
System.out.println(std1 == std2); //다른 주소 값이므로 false 반환
System.out.println(std1.equals(std2));
System.out.println(std1.hashCode()); //재정의된 해시코드 값
System.out.println(std2.hashCode());
System.out.println(System.identityHashCode(std1)); //실제 해시코드(가상메모리) 값을 반환
System.out.println(System.identityHashCode(std2));
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1.contentEquals(str2));
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
Integer i = 100;
System.out.println(i.hashCode()); //Integer의 hashCode() 값은 그 정수 값이 나옴
}
}

clone() 메서드
public class Student implements Cloneable {
private int studentNum;
private String studentName;
public Student(int studentNum, String studentName) {
this.studentNum = studentNum;
this.studentName = studentName;
}
public void setStudentName(String name) {
this.studentName = name;
}
public String toString() {
return studentNum + ", " + studentName;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student std = (Student)obj;
if (this.studentNum == std.studentNum) {
return true;
}
else return false;
}
return false;
}
@Override
public int hashCode() {
return studentNum;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
public class EqualsTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student std1 = new Student(100, "Lee");
std1.setStudentName("Kim");
Student copyStudent = (Student)std1.clone(); //생성 과정 없이 인스턴스의 상태를 그대로 복제해서 만드는 메서드
System.out.println(copyStudent);
System.out.println(System.identityHashCode(std1));
System.out.println(System.identityHashCode(copyStudent)); //또 다른 인스턴스가 생성된 것이므로 메모리 주소는 다름
}
}

String 클래스
String 선언하기
String str1 = new String("abc"); //힙 메모리에 인스턴스로 생성됨
String str2 = "abc"; //상수 풀에 있는 주소를 참조
힙 메모리에 인스턴스로 생성되는 경우와 상수 풀(constant pool)에 있는 주소를 참조하는 두 가지 방법
힙 메모리는 생성될 때마다 다른 주소 값을 가지지만, 상수 풀의 문자열은 모두 같은 주소 값을 가짐
public class StringTest {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1 == str2); //false 반환(다른 주소 값)
String str3 = "abc";
String str4 = "abc";
System.out.println(str3 == str4); //true 반환(같은 주소 값)
}
}
한 번 생성된 String은 불변(immutable)
String을 연결하면 기존의 String에 연결되는 것이 아닌 새로운 문자열이 생성됨 (메모리 낭비가 발생할 수도)
public class StringTest2 {
public static void main(String[] args) {
String java = new String("java");
String android = new String("android");
System.out.println(System.identityHashCode(java));
java = java.concat(android); //변수 java가 새로 생성된 "javaandroid"라는 메모리의 주소를 가리킴. 기존에 가리키던 "java"는 메모리에 그대로 남아있음
System.out.println(java);
System.out.println(System.identityHashCode(java));
}
}

“android”가 변수 java가 가리키던 기존의 “java” 메모리 뒤에 연결되는 것이 아니라 “javaandroid”라는 새로운 문자열이 생성되는 것이므로 메모리의 주소가 다름
StringBuilder, StringBuffer 활용하기
public class StringBuilderTest {
public static void main(String[] args) {
String java = new String("java");
String android = new String("android");
StringBuilder buffer = new StringBuilder(java);
System.out.println(System.identityHashCode(buffer));
buffer.append(android);
System.out.println(System.identityHashCode(buffer));
String test = buffer.toString();
System.out.println(test);
}
}

새로운 인스턴스가 생성되지 않고 기존의 문자열이 변경된 것이므로 같은 메모리 주소를 나타냄
text block 사용하기 (java 13)