0

简单代码:

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

4

1 回答 1

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");
        }

    }
}
于 2013-10-24T17:19:26.687 回答