IT TIP

"new String ()"도 변경 불가능합니까?

itqueen 2020. 10. 22. 23:49
반응형

"new String ()"도 변경 불가능합니까?


나는 잠시 동안 Java String을 공부했습니다. 다음 질문은 아래 게시물을 기반으로합니다.

Java String은 Java에서 String의 특별한
불변성입니다.

  1. 불변성 : 이제 불변성에 따라 String 클래스는 공통 풀 의 값 을 다른 장소 / 변수에서 재사용 할 수 있도록 설계되었습니다 . 이것은 다음 String과 같이 만들어진 경우 유효합니다.

    String a = "Hello World!"; 그러나 문자열을 다음과 같이 만들면

    String b = new String("Hello World!");왜 이것도 불변입니까? (아니면?). 여기에는 전용 힙 메모리가 있으므로 다른 변수에 영향을주지 않고 수정할 수 있어야합니다. 그래서 설계 상 String전체가 불변으로 간주되는 다른 이유 가 있습니까? 아니면 위의 가정이 잘못 되었습니까?

  2. 두 번째로 물어보고 싶었던 것은 공통 문자열 풀 에 관한 것이 었습니다 . 문자열 객체를 다음과 같이 생성하면

    String c = ""; 풀에 빈 항목이 생성 되었습니까?

이미 이것에 대한 게시물이 있습니까? 그렇다면 누군가가 링크를 공유 할 수 있습니까?


new String()String... 를 생성하는 표현식 이고 a String는 어떻게 생성 되든 불변입니다.

( new String()변경 가능 여부를 묻는 것은 무의미합니다. 이것은 값이 아니라 프로그램 코드입니다. 그러나 저는 그것이 당신이 정말로 의미하는 바가 아니라고 생각합니다.)


String c = "";풀에 생성 된 빈 항목 처럼 문자열 객체를 생성하면?

예; 즉, 빈 문자열에 대한 항목이 생성됩니다. 비어있는 것에 대해 특별한 것은 없습니다 String.

(현명하게 말하면,에 대한 풀 항목은 ""코드가 실행되기 훨씬 전에 생성됩니다. 사실, 코드가로드 될 때 생성되거나 ... 또는 그보다 더 일찍 생성됩니다.)


그래서 새로운 힙 객체도 불변인지 알고 싶었습니다.

네, 그렇습니다. 그러나 불변성은 String 객체의 기본 속성입니다. 모든 String개체.

당신은, 볼 StringAPI는 단순히 제공하지 않습니다 어떤 를 변경하는 방법 String. 따라서 ( 반사를 사용 하는 위험하고 어리석은 1 트릭을 제외하고) String.

그렇다면 목적은 무엇 이었습니까?.

Java String가 변경 불가능한 클래스로 설계된 주된 이유 는 단순성입니다. 핵심 문자열 클래스가 변경 불가능한 인터페이스를 제공하는 경우 올바른 프로그램을 작성하고 다른 사람의 코드를 읽고 추론하는 것이 더 쉽습니다.

두 번째 중요한 이유는의 불변성이 StringJava 보안 모델에 근본적인 영향을 미치기 때문입니다 . 그러나 나는 이것이 자바 1.0 이전의 원래 언어 디자인의 드라이버라고 생각하지 않습니다.

대답에 따르면 동일한 변수에 대한 다른 참조가 이유 중 하나라는 것을 수집합니다. 내가 이것을 이해하는 것이 옳은지 알려주십시오.

아뇨. 그것보다 더 근본적입니다. 간단히 말해서 모든 String객체는 불변입니다. 이를 이해하는 데 필요한 복잡한 특수 사례 추론은 없습니다. 그것은 단지 >>입니다 <<.

당신이 변경 가능한 "문자열 같은"자바 객체를 원하는 경우 기록을 위해, 당신은 사용할 수 있습니다 StringBuilder또는 StringBuffer. 그러나 이들은 String과 다른 유형입니다.


1-이러한 트릭이 (IMO) 위험하고 어리석은 이유는 문자열 풀을 통해 애플리케이션의 다른 부분에서 잠재적으로 공유하는 문자열 값에 영향을 미치기 때문입니다. 이것은 당신의 코드를 유지하는 다음 사람이 추적 할 가능성이 거의없는 방식으로 혼란을 일으킬 수 있습니다.


문자열은 인스턴스화 방법에 관계없이 변경할 수 없습니다.

1) 짧은 대답은 , new String()너무 불변이다.

수행 할 수있는 모든 변경 가능한 작업 (예 replace: toLowerCase등) String 은 원래 String 인스턴스에 영향주지 않고 새 인스턴스를 반환하기 때문 입니다.

.NET 용 Javadoc에서이를 확인할 수 있습니다 String. 노출 된 public메서드는 StringString인스턴스를 반환 하고 메서드를 호출 한 현재 인스턴스를 변경하지 않습니다.

이것은 당신이 주변 을 통과하거나 공유 할 때마다 가변성에 대해 생각할 필요가 없기 때문에 ( 누군가가 값을 변경할 것입니다) 멀티 스레드 환경에서 매우 유용 합니다 String. String가장 많이 사용되는 데이터 유형이 될 수 있으므로 설계자들은 우리 모두에게 항상 가변성에 대해 생각하지 않도록 축복했고 많은 고통을 덜어주었습니다.

불변성 허용 문자열 풀 또는 캐싱

다른 곳에서 동일한 String 값이 필요할 때 불변의 참조가 반환되는 것처럼 문자열의 내부 풀이 가능했던 것은 불변성 속성 때문입니다. 경우 String변경 가능했을 것이다 다음은 공유 불가능했을 것입니다 String메모리를 절약하기 위해이 같은의.

문자열 불변성은 풀링 때문이 아니지만 불변성에는 더 많은 이점이 있습니다.

스트링 인턴 또는 풀링은 플라이 웨이트 디자인 패턴 의 예입니다.

2) 네, 그것은 다른 어떤처럼 구금 될 것이다 String빈과 같이 String많이로도 String다른 같은 String경우.

참조 :


Java 라이브러리는 String객체가 구성되는 방법에 관계없이 객체가 불변 이라는 제약 조건을 중심으로 크게 최적화되어 있습니다. busing 을 생성하더라도 new해당 인스턴스를 전달하는 다른 코드는 값을 변경 불가능한 것으로 취급합니다. 이것은 Value Object 패턴의 예이며 모든 장점 (스레드 안전성, 개인용 사본을 만들 필요 없음)이 적용됩니다.

빈 문자열 ""String다른 것과 마찬가지로 합법적 인 개체이며 내부 내용이 없으며 모든 컴파일 타임 상수 문자열이 인턴되기 때문에 일부 런타임 라이브러리가 이미 해당 문자열에 추가되도록했습니다. 풀.


1) 불변 부분은 때문 이 아닙니다 . 그것은 단지 처음부터 풀을 가능하게합니다. 문자열은 종종 다른 함수에 인수로 전달되거나 다른 스레드와 공유됩니다. 문자열을 불변으로 만드는 것은 그러한 상황에서 추론을 더 쉽게하기위한 설계 결정이었습니다. 그래서 - String(- 바로하지와는 자바 가변 문자열을 가질 수 있다는 메모를 자바들, 항상 당신이 그들을 만드는 방법에 관계없이 불변 String클래스).

2) 네. 아마. 실제로 100 % 확실하지는 않지만 그럴 것입니다.


이것은 귀하의 질문에 대한 답은 아니지만 질문 뒤에 조작 가능한 변경 가능한 문자열을 원하면 StringBuilder클래스를 확인해야합니다.이 클래스 String똑같은 메서드를 많이 구현 하지만 메서드를 추가합니다. 현재 내용을 변경합니다.

만족스러운 방식으로 문자열을 빌드 한 후에는 s 만받는 라이브러리 루틴 및 기타 함수에 전달할 수 toString()있는 일반 문자열 로 변환하기 위해 문자열을 호출 하기 만하면 String됩니다 String.

또한, 모두 StringBuilderString구현 CharSequence이 모두 변경 가능한 불변의 문자열을 사용하여 자신의 코드에서 함수를 작성하려면 인터페이스는, 그래서, 당신은 어떤 취할를 선언 할 수 있습니다 CharSequence개체를.


로부터 자바 오라클 문서 :

문자열은 일정합니다. 값을 만든 후에는 변경할 수 없습니다 .

그리고 다시:

문자열 버퍼는 변경 가능한 문자열을 지원합니다. String 객체는 불변이기 때문에 공유 할 수 있습니다.

일반적으로 말해서 : "모든 원시"(또는 관련) 객체는 불변입니다 (제발 형식주의의 부족을 받아들이십시오).

Stack Overflow 관련 게시물 :

객체 풀에 대해 : 객체 풀은 불변과 관련이없는 자바 최적화입니다.


String is immutable은 객체를 어떻게 생성 했든 상관없이 객체 자체를 변경할 수 없음을 의미하며, 두 번째 질문은 항목을 생성합니다.


사실 그 반대입니다.

[...] String클래스는 공용 풀의 값을 다른 장소 / 변수에서 재사용 할 수 있도록 설계되었습니다.

아니요, String클래스는 변경 불가능하므로 프로그램의 다른 부분에서 수정 될 염려없이 인스턴스를 안전하게 참조 할 수 있습니다. 이것이 애초에 풀링이 가능한 이유입니다.

따라서 이것을 고려하십시오.

// this string literal is interned and referenced by 'a'
String a = "Hello World!";

// creates a new instance by copying characters from 'a'
String b = new String(a);

이제 새로 생성 된 b변수에 대한 참조를 생성하면 어떻게됩니까 ?

// 'c' now points to the same instance as 'b'
String c = b;

Imagine that you pass c (or, more specifically, the object it is referencing) to a method on a different thread, and continue working with the same instance on your main thread. And now imagine what would happen if strings were mutable.

Why is this the case anyway?

If nothing else, it's because immutable objects make multithreading much simpler, and usually even faster. If you share a mutable object (that would be any stateful object, with mutable private/public fields or properties) between different threads, you need to take special care to ensure synchronized access (mutexes, semaphores). Even with this, you need special care to ensure atomicity in all your operations. Multithreading is hard.

Regarding the performance implications, note that quite often copying the entire string into a new instance, in order to change even a single character, is actually faster than inducing an expensive context switch due to synchronization constructs needed to ensure thread-safe access. And as you've mentioned, immutability also offers interning possibilities, which means it can actually help reduce memory usage.

It's generally a pretty good idea to make as much stuff immutable as your can.


1) Immutability: String will be immutable if you create it using new or other way for security reasons

2) Yes there will be a empty entry in the string pool.

You can better understand the concept using the code

    String s1 = new String("Test");
    String s2 = new String("Test");
    String s3 = "Test";
    String s4 = "Test";

    System.out.println(s1==s2);//false
    System.out.println(s1==s3);//false
    System.out.println(s2==s3);//false
    System.out.println(s4==s3);//true

Hope this will help your query. You can always check the source code for String class in case of better understanding Link : http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java


1-String is immutable.See this:

Is a Java string really immutable?

So you can create it with many way.

2-Short answer: Yes will be empty.


Strings created will always be immutable regardless of how they are created.

Answers to your questions:

  1. The only difference is:
    When string is created like -- {String a = "Hello World!";} then only one object gets created.
    And when it is created like -- {String b = new String("Hello World!");} then two objects get created. The first one, because you have used 'new' keyword and the second one because of the String property.

  2. Yes, for sure. There will be an empty entry created in the pool.


String is immutable because it does not provide you with a mean to modify it. It is design to avoid any tampering (it is final, the underlying array is not supposed to be touched ...).

Identically, Integer is immutable, because there is no way to modify it.

It does not matter how you create it.


Immutability is not a feature of new, it is a feature of the class String. It has no mutator methods, so it immutable.


 String A = "Test"
 String B = "Test"

Now String B called"Test".toUpperCase()which change the same object into"TEST", soAwill also be"TEST"` which is not desirable.


Note that in your example, the reference is changed and not the object it refers to, i.e. b as a reference may be changed and refer to a new object. But that new object is immutable, which means its contents will not be changed "after" calling the constructor.

You can change a string using b=b+"x"; or b=new String(b);, and the content of variable a seem to change, but don't confuse immutability of a reference (here variable b) and the object it is referring to (think of pointers in C). The object that the reference is pointing to will remain unchanged after its creation.

If you need to change a string by changing the contents of the object (instead of changing the reference), you can use StringBuffer, which is a mutable version of String.

참고URL : https://stackoverflow.com/questions/21375659/is-new-string-immutable-as-well

반응형