String+의 기본 구현 원리

1308 단어
문제를 내서 답이 무엇인지 생각해 보아라
String s=null;
s=s+"abc";
System.out.println(s);

역시 답은 내 생각과 다르다. 인터럽트 디버깅으로 실행 원리를 살펴보자.
public StringBuilder() {  // StringBuilder 
    super(16);
}

AbstractStringBuilder(int capacity) {
    value = new char[capacity];
}

append 연결 호출 첫 번째 String 즉 s
public StringBuilder append(String str) {
    super.append(str);
    return this;
}
public AbstractStringBuilder append(String str) {
    if (str == null)
        return appendNull();  //s null   
    int len = str.length();
    ensureCapacityInternal(count + len);
    str.getChars(0, len, value, count);
    count += len;
    return this;
}

StringBuilder 객체에 "null"값 지정
private AbstractStringBuilder appendNull() {
    int c = count;
    ensureCapacityInternal(c + 4);
    final char[] value = this.value;
    value[c++] = 'n';
    value[c++] = 'u';
    value[c++] = 'l';
    value[c++] = 'l';
    count = c;
    return this;
}

그리고 append 방법으로 "abc"를 연결합니다.
결과는 자연히:nullabc
 
그리고 제목을 바꿉니다.
String s=new String();
s=s+"abc";
System.out.println(s);

신입 흰둥이의 학습 노트, 무슨 문제가 있으면 지적해 주십시오.

좋은 웹페이지 즐겨찾기