public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
private final char value[]; // 문자열을 저장하는 배열 (불변성 유지)
private final int count; // 문자열의 길이
// String의 생성자
public String() {
this.value = new char[0]; // 빈 문자열을 초기화
this.count = 0;
}
public String(String original) {
this.value = original.value; // 새로운 문자열을 원본에서 복사
this.count = original.count;
}
public int length() {
return this.count;
}
public char charAt(int index) {
if (index < 0 || index >= count) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return new String(value, beginIndex, endIndex - beginIndex);
}
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
// 그 외 다양한 메서드들...
}
- 내용을 변경할 수 없는 불변(immutable) 클래스
- 덧셈 연사자(+)를 이용한 문자열 결합은 할때마다 새로운 객체가 만들어져서 성능이 떨어짐 문자열의 결합이나 변경이 잦다면, 내용을 변경가능한 StringBuffer를 사용
ch9-8 문자열의 비교
- String str = "abc"; 와 String str = new String("abc"); 의 비교 == : 객체의 참조(메모리 위치)를 비교. equals() : 객체의 내용을 비교. 결론 : 두 객체의 내용이 같은지를 비교하고 싶다면, equals() 메서드를 사용하는 것이 필수적이다. ==를 사용하면 의도치 않은 결과를 초래할 수 있다.
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1 == str2); // false, 서로 다른 메모리 위치
System.out.println(str1.equals(str2)); // true, 같은 내용
ch9-9 문자열 리터럴
- 문자열 리터럴은 프로그램 실행시 자동으로 생성된다. (constant pool에 저장 :상수 저장소) - 같은 내용의 문자열 리터럴은 하나만 만들어진다.
ch9-10 빈 문자열("",Empty String)
- 내용이 없는 문자열. 크가가 0인 char형 배열을 저장하는 문자열
String str ="";//str을 빈 문자열로 초기화
- 길이가 0인 배열을 생성하는 것은 어느 타입이나 가능
char[] chArr = new char[0]; //길이가 0인 char배열
int[] iArr = {}; // 길이가 0인 int배열