gpt4 book ai didi

java - 为什么人们使用 new String 而不是某些值?

转载 作者:行者123 更新时间:2023-12-01 13:57:00 24 4
gpt4 key购买 nike

简单代码:

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 相同的故事.

最佳答案

两者的区别
字符串 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");
}

}
}

关于java - 为什么人们使用 new String 而不是某些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19572408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com