为什么人们使用新的String而不是某些值?

时间:2013-10-24 17:16:49

标签: java

简单代码:

class MyClass<T>
{

private T t;

    public void add(T t)
    {
       this.t = t;
    }

    public T get()
    {
     return t;   
    }  
}

然后:

public static void main(String[] args) {

    MyClass<String> StringClass = new MyClass<>();

    StringClass.add("This is string");

 // **Or actually it can be:  StringClass.add(new String("This is string"));**

我看到人们使用StringClass.add(new String("This is string"))而不是简单版StringClass.add("This is string")。有什么区别?

Integers相同的故事。

1 个答案:

答案 0 :(得分:1)

之间的区别 String foo = "bar"

String foo = new String("bar")

是第一个没有创建新的String对象,而是在您创建的现有String值中查找该值。这称为实习值。这节省了内存。

具有new关键字的关键字为您创建的String对象分配新内存。

public class StringInternExample {
    public static void main(String[] args) {
        String foo1 = "bar";
        String foo2 = "bar";

        String foo3 = new String("Hello, Kitty");
        String foo4 = new String("Hello, Kitty");

        if(foo1 == foo2){ // compare addresses. Same address = no new memory assigned
            System.out.println("No new memory has been assigned for foo2");
        }

        if(!(foo3 == foo4)){ // compare addresses. Different addresses = new memory
            System.out.println("New Memory has been assigned for foo4");
        }

    }
}
相关问题