본문 바로가기

Java/기본

[Java] 유용한 클래스 - StringBuffer, StringBuilder클래스

개요

String 클래스가 생성후 수정할 수 없는 것에 비해, StringBuffer클래스와 StringBuilder클래스는 문자열 생성후에 얼마든지 수정이 가능하다. 문자열이 자주 변경될 상황이라면 String 클래스보다는 StringBuffer 혹은 StringBuilder 클래스 사용 검토가 필요하다.

 

StringBuffer 클래스의 주요 메서드

메서드 리턴타입 내용
append(String str) StringBuffer 현재 StringBuffer객체에 str값을 덧붙임
capacity() int 현재 용량
delete(int start, int end) StringBuffer start부터 end까지 삭제
insert(int offset, String str) StringBuffer offset 위치에 str 넣기
replace(int start, int end, String str) StringBuffer start부터 end까지
setLength(int A) void A만큼 길이를 새로 설정. 보통 0을 넣어서 buffer를 비울때 사용
toString() String StringBuffer객체가 담고 있는 문자열을 String객체로 반환함
ensureCapacity(int capacity) void StringBuffer객체의 기본 용량 변경

 

StringBuffer 용량

초기에 capacity를 설정한 경우를 제외하면, StringBuffer클래스를 생성시 할당되는 용량은 실제 buffer에 들어간 문자열 크기보다 16문자가 더 긴 공간을 차지하게 된다. String 클래스와는 달리 StringBuffer클래스는 문자열 수정이 용이한데, 이 작업을 위해 16문자크기 만큼 추가로 할당을 해주기 때문이다.

 

public class StringBufferEx {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("he");
        printCapacityAndLength(sb); //capacity : 18 | length : 2

        sb.append("llo");
        printCapacityAndLength(sb); //capacity : 18 | length : 5

        sb.append("world");
        printCapacityAndLength(sb); //capacity : 18 | length : 10

        sb.append("iloveyou");
        printCapacityAndLength(sb); //capacity : 18 | length : 18

        sb.append("1234567890AB");
        printCapacityAndLength(sb); //capacity : 38 | length : 30

        sb.append("testTest");
        printCapacityAndLength(sb); //capacity : 38 | length : 38

        sb.append("!");
        printCapacityAndLength(sb); //capacity : 78 | length : 39

        sb.append("12345678901234567890123456789012345678901234567890");
        printCapacityAndLength(sb); //capacity : 158 | length : 89

        sb.delete(10, sb.length());
        printCapacityAndLength(sb); //capacity : 158 | length : 81

        System.out.println(sb.toString());  //helloworld

        sb.setLength(0);
        printCapacityAndLength(sb); //capacity : 158 | length : 0
        sb.trimToSize();
        printCapacityAndLength(sb); //capacity : 0 | length : 0
    }

    static void printCapacityAndLength(StringBuffer sb){
        System.out.println("capacity : "+ sb.capacity()+ " | length : "+ sb.length());
    }
}

 

처음에 할당한 문자열 length는 2이고 capacity는 16만큼 더 긴 18만큼 할당되었다. append()를 호출하여 문자열을 추가해도 capacity는 변하지 않다가 초기에 설정된 용량을 초과하면 그만큼 더많은 크기를 할당받는다.

기존에 할당된 문자열이 길수록 추가로 할당되는 용량도 더 커지는 것을 확인할 수 있다. 또한, 한번 커진 용량은 문자열이 줄어들어도 변하지 않는다. trimToSize() 메서드로 현재 문자열길이만큼 용량을 조정해줘야 적용된다.

 

 

 

StringBuffer vs StringBuilder

StringBuffer 클래스는 다중 스레드를 지원하여 안전하게 문자열을 처리할 수 있도록 한다. 당연히 동기화(synchronize)과정이 필요하기 때문에 StringBuilder보다는 느릴 수 있다. 단일 스레드 환경에서는 속도차이가 미미하다.