문제

I have two classes using the same String value, and both storing them as a final private field.

public class Foo{
    private final String str;
    private final Bar bar; //notice this

    public Foo(String in){
        this.str=in;
        this.bar=new Bar(in);       //option 1
        this.bar=new Bar(this.str); //option 2
    }
}

And here comes Bar:

public class Bar{
    private final String boo;

    public Bar(String in){
        this.boo=in;
    }
}
  • Does Java store the same object everywhere, or does it make a copy for each instance*?
  • Is your answer the same for both option 1 and 2?

*Intuition hints at the former but you can never be sure with Java.

Side question:
What I'm trying to do is this: Foo does some processing on str and uses Bar as a utility class. Conceptually Foo and str are closely linked together, but apart from the constructor, Foo doesn't touch str directly again, but only through Bar.

I thought about removing str from Foo's fields in fear of Java allocating the same string twice, which prompted this question. But from a software engineering / code correctness standpoint, should I remove it?

도움이 되었습니까?

해결책

Since you don't instantiate another String instance, your options are all the same reference (in this example).

Considering your initial call(s), we could force them to have different reference values (I don't know why you would do this, and there are consequences - namely growing the intern cache);

this.str=in;
this.bar=new Bar(in);                     // option 1
this.bar=new Bar(this.str);               // option 2

This will change the references.

this.str = new String(in);                // <-- create a new String from in.
this.bar = new Bar(in);                   // <-- keeps the original reference to in.
StringBuilder sb = new StringBuilder(in); // <-- create a StringBuilder.
this.bar = new Bar(sb.toString());        // <-- create another String.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top