본문 바로가기
> JAVA/Class 클래스

[Java] 2019.09- [Class] StringBuffer

by bky373 2020. 9. 20.

 

StringBuffer

 

쇠뿔도 단김에 빼라고 StringBuilder를 봤으니 이제 StringBuffer도 보려 한다.

단일스레드에선 StringBuilder가 빠르고, 다중스레드에선 StringBuffer가 안전하다 했는데

그거 빼고는 느낌상 왠지 큰 차이는 없을 듯하다.

자세한 건 이제 아래 내용을 통해 찬찬히 봐야겠다.

급하다면 아래 요약 부분을 참고하자!

 

 

역시나 생성자나 메소드 등에 대한 설명은 뒤로 하고

우선 StringBuffer클래스가 본질적으로 가지고 있는 속성이나 특징 등을 살펴보려 한다.

 

public final class StringBuffer extendsObject
implementsSerializable,Comparable<StringBuffer>,CharSequence

A thread-safe, mutable sequence of characters. A string buffer is like aString, but can be modified.

> 스레드에서 안전한 변경가능한 문자들의 시퀀스이다. 스트링버퍼는 String과 비슷한데, 얘는 수정이 가능하다.

At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

> 언제든지 특정한 문자들의 시퀀스를 포함하지만 길이와 내용은 메소드 호출에 따라 달라질 수 있다.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

> 스트링버퍼는 다중스레드에서 안전하다. 메소드들은 필요한 경우에 동기화되며, 어떤 특정한 객체가 행하는 모든 활동들이 각 스레드에서 발생시킨 메소드들의 호출과 동일한 순서로 순차적으로 일어난다.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type.

> StringBuffer가 하는 주된 활동은 append메소드와 insert메소드가 있다. 이 메소드들은 어떤 유형의 데이터든 접근할 수 있도록 오버로드돼 있는 것들이다.

Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

> 각각의 것들은 입력된 자료들을 문자열로 변환하고, 그 문자열의 문자들을 스트링버퍼에 덧붙이거나 삽입한다. append 메소드는 항상 버퍼 마지막에 문자들을 덧붙이고, insert 메소드는 명시된 특정지점에 문자열들을 더한다(끼운다).

For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet".

> 예를 들어, "start"를 내용으로 하는 스트링버퍼 객체 z가 있다고 하자. z.append("le")를 호출하면 스트링버퍼는 "startle"가 될 것이고, 반면 z.insert(4, "le")를 호출하면 스트링버퍼는 "starlet"이 될 것이다.

In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

> 일반적으로, 스트링버퍼 객체 sb가 있다면, sb.append(x)는 sb.insert(sb.length(),x)한 것과 같다.

Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence), this class synchronizes only on the string buffer performing the operation, not on the source.

> 소스시퀀스와 관련된 어떤 활동이 있을 때마다(소스시퀀스에 append를 한다거나 insert를 한다거나), 이 클래스는 그 활동을 수행한 스트링버퍼에서만 동기화된다(소스가 아니라).

Note that while StringBuffer is designed to be safe to use concurrently from multiple threads, if the constructor or the append or insert operation is passed a source sequence that is shared across threads, the calling code must ensure that the operation has a consistent and unchanging view of the source sequence for the duration of the operation.

> StringBuffer는 다중스레드에서 동시에 안전하게 사용할 수 있도록 설계되었다. 만약 다중스레드에 공유된 소스시퀀스를 생성자나 append/ insert메소드에 전달한다고 해보자. 그 작업이 수행되는 동안 호출한(call한) 코드는 소스시퀀스가 변하지 않는다는 것을 확실히 해줘야 한다.

This could be satisfied by the caller holding a lock during the operation's call, by using an immutable source sequence, or by not sharing the source sequence across threads.

> 그러기 위해caller가 그 작업을 호출하는 동안에 lock을 갖고 있어야 되는데, 변경불가능한 소스시퀀스를 사용하거나, 소스시퀀스를 여러 스레드에 공유하지 않을 때(lock이 걸려 있을 때) 가능하다.

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

> 모든 스트링버퍼는 용량을 갖고 있다. 스트링버퍼 안에 있는 문자시퀀스라면 그 길이가 용량을 초과하지 않는다. 초과하지 않으면 굳이 내부 버퍼를 새로 할당할 필요도 없다. 만약 내부 버퍼가 오버플로되면(흘러넘치면) 버퍼는 자동으로 커진다.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause aNullPointerExceptionto be thrown.

> 별다른 언급이 없는 한, 생성자 또는 메소드에 null인수를 전달하면NullPointerException을 발생시킬 것이다.

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread,StringBuilder.

> JDK5 부터는 단일 스레드에서 사용하도록 이 클래스와 똑같은 StringBuilder클래스가 추가되었다.(예지력 상승..!)

The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

> StringBuilder클래스가 더 빠르기 때문에 동기화를 하지 않는 경우라면 StringBuffer클래스 대신 이 클래스를 사용하라.

 

API Note:

StringBuffer implements Comparable but does not overrideequals. Thus, the natural ordering of StringBuffer is inconsistent with equals. Care should be exercised if StringBuffer objects are used as keys in a SortedMap or elements in a SortedSet. SeeComparable,SortedMap, orSortedSetfor more information.

> StringBuffer는 Comparable을 구현하나 equals를 재정의하지는 못한다. 그래서 둘 간의 자연적 순서?는 일치하지 않는다. SortedMap의 key나 SortedSet의 element로 StringBuffer객체를 사용할 때는 각별히 주의해야 한다.

Since:

1.0

See Also:

StringBuilder,String,Serialized Form

 

 


*** 요약 ***

 

StringBuffer는 버퍼 안에 있는 문자들의 연결체이다. 곧

문자들을 연결해놓은 클래스를 말하며 append,

insert 등 *메소드를 통해수정 가능하다.

(여기까진 StringBuilder와 같다.)

 

그러나 StringBuffer보다 먼저 태어났지만느리다는 단점이 있고,

반대로 이걸 대신할 무기인

다중스레드에선 안전하다는 장점이 있다.

 

 

*StringBuffer내 메소드는 반환타입이 StringBuffer인 경우가 많다. String으로 사용하고자 할 때 메소드 뒤에 ".toString()"까지 붙여주는 것 잊지말자!!


참고 :StringBuilder에대해

https://blog.naver.com/bo373/221644127051


 

 

출처 : https://docs.oracle.com/en/java/javase/12/docs/api/

 

'> JAVA > Class 클래스' 카테고리의 다른 글

[Java] 2019.09- [Class] BufferedReader  (0) 2020.09.22
[Java] 2019.09- [Class] ArrayList<E>  (0) 2020.09.20
[Java] 2019.09- [Class] StringBuilder  (0) 2020.09.20

댓글