티스토리 뷰
StringBuilder
자바에는 String 이외에 StringBuilder라는 것이 있다.
String이 있는데 굳이 StringBuilder를 사용해야 할까 ?
이에 대한 답변은 아래의 링크에서 설명해주고 있다.https://www.codejava.net/java-core/the-java-language/why-use-stringbuffer-and-stringbuilder-in-java
자바의 String은 Immutable(불변)하다는 성질을 갖고 있기 때문에 한 문자열에 다른 문자열을 더할 경우(concat) 해당 문자열 뒤에 새로운 문자열을 이어붙이는 것이 아닌 새로운 메모리 공간을 할당하여 이전 문자열에 새로운 문자열을 붙인 문자열을 넣는다. 또한, 이전에 있던 문자열은 JVM의 GC가 처리하게 된다.
이러한 부분에 의해 만약 아래와 같은 구문을 사용하게 되면 오버헤드가 커지면서 성능저하가 발생하게 된다.
String a = "hello";
String b = "World";
for (int i = 0; i < 1000000; i++) {
a += b;
}
아래의 그래프는 String 메소드에 대해 시간복잡도를 비교한 것인데 String의 concat 연산이 가장 성능저하가 심한 것으로 나타난다
위와 같은 문제점을 해결하기 위해 StringBuilder가 등장하게 되었다.
StringBuilder는 String과 다르게 mutable한 성질을 갖고 있다. 즉, 값이 변할 수 있다는 것이다.
.append(), .delete()와 같은 메서드를 통해 String의 값을 변동시킬 수 있으며 이는 매번 새로운 메모리 공간을 할당하는 String의 +, .concat 연산에 비해 뛰어난 성능을 보여준다.
StringBuilder의 생성자
Constructor Summary
StringBuilder()
Constructs a string builder with no characters in it and an initial capacity of 16 characters.
|
StringBuilder(CharSequence seq)
Constructs a string builder that contains the same characters as the specified CharSequence.
|
StringBuilder(int capacity)
Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
|
StringBuilder(String str)
Constructs a string builder initialized to the contents of the specified string.
|
StringBuilder의 주요 메서드
Method Summary
StringBuilder | append(boolean b)
Appends the string representation of the boolean argument to the sequence.
|
StringBuilder | append(char c)
Appends the string representation of the char argument to this sequence.
|
StringBuilder | append(char[] str)
Appends the string representation of the char array argument to this sequence.
|
StringBuilder | append(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array argument to this sequence.
|
StringBuilder | append(CharSequence s)
Appends the specified character sequence to this Appendable.
|
StringBuilder | append(CharSequence s, int start, int end)
Appends a subsequence of the specified CharSequence to this sequence.
|
StringBuilder | append(double d)
Appends the string representation of the double argument to this sequence.
|
StringBuilder | append(float f)
Appends the string representation of the float argument to this sequence.
|
StringBuilder | append(int i)
Appends the string representation of the int argument to this sequence.
|
StringBuilder | append(long lng)
Appends the string representation of the long argument to this sequence.
|
StringBuilder | append(Object obj)
Appends the string representation of the Object argument.
|
StringBuilder | append(String str)
Appends the specified string to this character sequence.
|
StringBuilder | append(StringBuffer sb)
Appends the specified StringBuffer to this sequence.
|
StringBuilder | appendCodePoint(int codePoint)
Appends the string representation of the codePoint argument to this sequence.
|
int | capacity()
Returns the current capacity.
|
char | charAt(int index)
Returns the char value in this sequence at the specified index.
|
int | codePointAt(int index)
Returns the character (Unicode code point) at the specified index.
|
int | codePointBefore(int index)
Returns the character (Unicode code point) before the specified index.
|
int | codePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this sequence.
|
StringBuilder | delete(int start, int end)
Removes the characters in a substring of this sequence.
|
StringBuilder | deleteCharAt(int index)
Removes the char at the specified position in this sequence.
|
void | ensureCapacity(int minimumCapacity)
Ensures that the capacity is at least equal to the specified minimum.
|
void | getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
|
int | indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
|
int | indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
|
StringBuilder | insert(int offset, boolean b)
Inserts the string representation of the boolean argument into this sequence.
|
StringBuilder | insert(int offset, char c)
Inserts the string representation of the char argument into this sequence.
|
StringBuilder | insert(int offset, char[] str)
Inserts the string representation of the char array argument into this sequence.
|
StringBuilder | insert(int index, char[] str, int offset, int len)
Inserts the string representation of a subarray of the str array argument into this sequence.
|
StringBuilder | insert(int dstOffset, CharSequence s)
Inserts the specified CharSequence into this sequence.
|
StringBuilder | insert(int dstOffset, CharSequence s, int start, int end)
Inserts a subsequence of the specified CharSequence into this sequence.
|
StringBuilder | insert(int offset, double d)
Inserts the string representation of the double argument into this sequence.
|
StringBuilder | insert(int offset, float f)
Inserts the string representation of the float argument into this sequence.
|
StringBuilder | insert(int offset, int i)
Inserts the string representation of the second int argument into this sequence.
|
StringBuilder | insert(int offset, long l)
Inserts the string representation of the long argument into this sequence.
|
StringBuilder | insert(int offset, Object obj)
Inserts the string representation of the Object argument into this character sequence.
|
StringBuilder | insert(int offset, String str)
Inserts the string into this character sequence.
|
int | lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
|
int | lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.
|
int | length()
Returns the length (character count).
|
int | offsetByCodePoints(int index, int codePointOffset)
Returns the index within this sequence that is offset from the given index by codePointOffset code points.
|
StringBuilder | replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the specified String.
|
StringBuilder | reverse()
Causes this character sequence to be replaced by the reverse of the sequence.
|
void | setCharAt(int index, char ch)
The character at the specified index is set to ch.
|
void | setLength(int newLength)
Sets the length of the character sequence.
|
CharSequence | subSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
|
String | substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
|
String | substring(int start, int end)
Returns a new String that contains a subsequence of characters currently contained in this sequence.
|
String | toString()
Returns a string representing the data in this sequence.
|
void | trimToSize()
Attempts to reduce storage used for the character sequence.
|
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html?is-external=true
알아보기 쉽게 정리하자면 아래와 같다.
- .append(): 문자열을 이어붙인다.
- .insert(int offset, String str): offset 위치에 str을 삽입한다.
- .replace(): 첫번째와 두번째 파라미터로 받는 숫자 인덱스에 위치한 문자열을 대체한다.
- .substring(int start, (int end)): 인덱싱. 파라미터가 하나라면 해당 인덱스부터 끝까지, 두개라면 시작점과 끝점-1 까지 인덱싱
- .deleteCharAt(int index): 인덱스에 위치한 문자 하나를 삭제한다.
- .delete(int start, int end): start 부터 end-1 까지의 문자를 삭제한다.
- .toString(): String으로 변환한다.
- .reverse(): 해당 문자 전체를 뒤집는다.
- .setCharAt(int index, String s): index 위치의 문자를 s로 변경
- .setLength(int len): 문자열 길이 조정, 현재 문자열보다 길게 조정하면 공백으로 채워짐, 현재 문자열보다 짧게 조정하면 나머지 문자는 삭제
- .trimToSize(): 문자열이 저장된 char[] 배열 사이즈를 현재 문자열 길이와 동일하게 조정,