简单代码:
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
相同的故事。
答案 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");
}
}
}