Java "text" 和 new String("text") 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3052442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between "text" and new String("text")?
提问by user368141
What is the difference between these two following statements?
下面这两个陈述有什么区别?
String s = "text";
String s = new String("text");
采纳答案by polygenelubricants
new String("text");
explicitly creates a new and referentially distinct instance of a String
object; String s = "text";
may reuse an instance from the string constant poolif one is available.
new String("text");
显式地创建一个新的和引用不同的String
对象实例;如果可用,String s = "text";
可以重用字符串常量池中的一个实例。
You very rarelywould ever want to use the new String(anotherString)
constructor. From the API:
您很少会想要使用new String(anotherString)
构造函数。从API:
String(String original)
: Initializes a newly createdString
object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since strings are immutable.
String(String original)
: 初始化一个新创建的String
对象,使其表示与参数相同的字符序列;换句话说,新创建的字符串是参数字符串的副本。除非需要原始的显式副本,否则不需要使用此构造函数,因为字符串是不可变的。
Related questions
相关问题
- Java Strings: “String s = new String(”silly“);”
- Strings are objects in Java, so why don't we use ‘new' to create them?
What referential distinction means
指称区分是什么意思
Examine the following snippet:
检查以下代码段:
String s1 = "foobar";
String s2 = "foobar";
System.out.println(s1 == s2); // true
s2 = new String("foobar");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
==
on two reference types is a reference identity comparison. Two objects that are equals
are not necessarily ==
. It is usually wrong to use ==
on reference types; most of the time equals
need to be used instead.
==
在两个引用类型上是引用标识比较。equals
不一定是的两个对象==
。==
在引用类型上使用通常是错误的;大部分时间都equals
需要改用。
Nonetheless, if for whatever reason you need to create two equals
but not ==
string, you canuse the new String(anotherString)
constructor. It needs to be said again, however, that this is verypeculiar, and is rarely the intention.
尽管如此,如果出于某种原因需要创建两个equals
而不是==
字符串,则可以使用new String(anotherString)
构造函数。然而,需要再次说明的是,这是非常奇特的,而且很少是本意。
References
参考
Related issues
相关问题
回答by polygenelubricants
One creates a String in the String Constant Pool
在字符串常量池中创建一个字符串
String s = "text";
the other one creates a string in the constant pool ("text"
) and another string in normal heap space (s
). Both strings will have the same value, that of "text".
另一个在常量池 ( "text"
) 中创建一个字符串,并在普通堆空间 ( s
) 中创建另一个字符串。两个字符串将具有相同的值,即“文本”的值。
String s = new String("text");
s
is then lost (eligible for GC) if later unused.
s
如果以后未使用,则丢失(有资格进行 GC)。
String literals on the other hand are reused. If you use "text"
in multiple places of your class it will in fact be one and only one String (i.e. multiple references to the same string in the pool).
另一方面,字符串文字被重用。如果你"text"
在你的类的多个地方使用它实际上将是一个并且只有一个字符串(即对池中同一个字符串的多个引用)。
回答by b_erb
Think of "bla"
being a magic factory like Strings.createString("bla")
(pseudo). The factory holds a pool of all strings yet created this way.
想象一下"bla"
像Strings.createString("bla")
(伪)一样的魔法工厂。工厂拥有一个以这种方式创建的所有字符串的池。
If it gets invoked, it checks if there is already string in the pool with this value. If true, it returns this string object, hence to strings obtained this way are indeed the same object.
如果它被调用,它会检查池中是否已经存在具有此值的字符串。如果为真,则返回这个字符串对象,因此以这种方式获得的字符串确实是同一个对象。
If not, it creates a new string object internally, saves it in the pool and then returns it. Thus, when the same string value is queried the next time, it returns the same instance.
如果没有,它会在内部创建一个新的字符串对象,将它保存在池中,然后返回它。因此,当下次查询相同的字符串值时,它返回相同的实例。
Manually creating new String("")
overrides this behaviour by bypassing the string literal pool. So equality should always be checked using equals()
which compares the character sequence instead of the object reference equality.
手动创建new String("")
通过绕过字符串文字池来覆盖此行为。因此,应始终使用equals()
which 比较字符序列而不是对象引用相等性来检查相等性。
回答by Shashank T
One simple way to understand the difference is below:-
理解差异的一种简单方法如下:-
String s ="abc";
String s1= "abc";
String s2=new String("abc");
if(s==s1){
System.out.println("s==s1 is true");
}else{
System.out.println("s==s1 is false");
}
if(s==s2){
System.out.println("s==s2 is true");
}else{
System.out.println("s==s2 is false");
}
output is
输出是
s==s1 is true
s==s2 is false
Thus new String() will always create a new instance.
因此 new String() 将始终创建一个新实例。
回答by fastcodejava
Although it looks the same from a programmers point of view, it has big performance impact. You would want to use the first form almost always.
尽管从程序员的角度来看它看起来是一样的,但它对性能有很大的影响。您几乎总是希望使用第一种形式。
回答by Braj
String literalswill go into String Constant Pool.
字符串文字将进入String Constant Pool。
The below snapshot might help you to understand it visuallyto remember it for longer time.
下面的快照可能会帮助您直观地理解它,以便更长时间地记住它。
Object creation line by line:
逐行创建对象:
String str1 = new String("java5");
Using string literal "java5" in the constructor, a new string value is stored in string constant pool. Using new operator, a new string object is created in the heap with "java5" as value.
在构造函数中使用字符串字面量“java5”,一个新的字符串值存储在字符串常量池中。使用 new 运算符,在堆中创建一个新的字符串对象,并以“java5”为值。
String str2 = "java5"
Reference "str2" is pointed to already stored value in string constant pool
引用“str2”指向字符串常量池中已经存储的值
String str3 = new String(str2);
A new string object is created in the heap with the same value as reference by "str2"
在堆中创建一个新的字符串对象,其值与“str2”引用的值相同
String str4 = "java5";
Reference "str4" is pointed to already stored value in string constant pool
引用“str4”指向字符串常量池中已经存储的值
Total objects : Heap - 2, Pool - 1
对象总数:堆 - 2,池 - 1
回答by SDC
@Braj : i think u have mentioned the other way around. Please correct me if i am wrong
@Braj:我想你已经提到了相反的方式。如果我错了,请纠正我
Object creation line by line:
逐行创建对象:
String str1 = new String("java5")
String str1 = new String("java5")
Pool- "java5" (1 Object)
Heap - str1 => "java5" (1 Object)
String str2 = "java5"
字符串 str2 = "java5"
pool- str2 => "java5" (1 Object)
heap - str1 => "java5" (1 Object)
String str3 = new String(str2)
字符串 str3 = 新字符串(str2)
pool- str2 => "java5" (1 Object)
heap- str1 => "java5", str3 => "java5" (2 Objects)
String str4 = "java5"
字符串 str4 = "java5"
pool - str2 => str4 => "java5" (1 Object)
heap - str1 => "java5", str3 => "java5" (2 Objects)
回答by Jayesh
String str = new String("hello")
It will check whether String constant pool already contains String "hello"? If present then it will not add an entry in String constant pool. If not present then it will add an entry in String constant pool.
它将检查字符串常量池是否已经包含字符串“hello”?如果存在,则不会在字符串常量池中添加条目。如果不存在,那么它将在字符串常量池中添加一个条目。
An object will be created in a heap memory area and str
reference points to object created in heap memory location.
一个对象将在堆内存区域中创建,并str
引用指向在堆内存位置中创建的对象。
if you want str
reference to point object containing in String constant pool then one has to explicitly call str.intern();
如果要str
引用包含在字符串常量池中的点对象,则必须显式调用str.intern();
String str = "world";
It will check whether String constant pool already contains String "hello"? If present then it will not add an entry in String constant pool. If not present then it will add an entry in String constant pool.
它将检查字符串常量池是否已经包含字符串“hello”?如果存在,则不会在字符串常量池中添加条目。如果不存在,那么它将在字符串常量池中添加一个条目。
In both the above case, str
reference points to String "world"
present in Constant pool.
在上述两种情况下,str
引用指向"world"
常量池中存在的字符串。
回答by Amritansh
Any String literal gets created inside string literal pool and the pool doesn't allow any duplicates. Thus if two or more string objects are initialized with the same literal value then all objects will point to the same literal.
任何字符串文字都在字符串文字池中创建,并且池不允许任何重复。因此,如果两个或多个字符串对象使用相同的文字值初始化,则所有对象都将指向相同的文字。
String obj1 = "abc";
String obj2 = "abc";
"obj1" and "obj2" will point to the same string literal and the string literal pool will have only one "abc" literal.
“obj1”和“obj2”将指向相同的字符串文字,字符串文字池将只有一个“abc”文字。
When we create a String class object using the new keyword the string thus created is stored in heap memory. Any string literal passed as parameter to the constructor of String class however is stored in string pool. If we create multiple objects using the same value with the new operator a new object will be created in the heap each time, because of this new operator should be avoided.
当我们使用 new 关键字创建 String 类对象时,由此创建的字符串存储在堆内存中。然而,作为参数传递给 String 类的构造函数的任何字符串文字都存储在字符串池中。如果我们使用相同的值和 new 操作符创建多个对象,每次都会在堆中创建一个新对象,因为应该避免使用这个 new 操作符。
String obj1 = new String("abc");
String obj2 = new String("abc");
"obj1" and "obj2" will point to two different objects in the heap and the string literal pool will have only one "abc" literal.
“obj1”和“obj2”将指向堆中的两个不同对象,字符串文字池将只有一个“abc”文字。
Also something that is worth noting with regards to the behavior of strings is that any new assignment or concatenation done on string creates a new object in memory.
关于字符串的行为还有一点值得注意的是,对字符串进行的任何新赋值或连接都会在内存中创建一个新对象。
String str1 = "abc";
String str2 = "abc" + "def";
str1 = "xyz";
str2 = str1 + "ghi";
Now in the above case:
Line 1: "abc" literal is stored in string pool.
Line 2: "abcdef" literal gets stored in the string pool.
Line 3: A new "xyz" literal is stored in the string pool and "str1" starts to point to this literal.
Line 4: Since the value is generated by appending to another variable the result is stored in the heap memory and the literal being appended "ghi" will be checked for its existence in the string pool and will be created since it doesn't exist in the above case.
现在在上面的情况下:
第 1 行:“abc”文字存储在字符串池中。
第 2 行:“abcdef”文字存储在字符串池中。
第 3 行:一个新的“xyz”字面量存储在字符串池中,“str1”开始指向这个字面量。
第 4 行:由于该值是通过附加到另一个变量生成的,因此结果存储在堆内存中,并且将检查附加的文字“ghi”是否存在于字符串池中,并将创建,因为它不存在于上述情况。
回答by Syed Babar Ali Shah 3261-FBASB
When you store a String as
当您将字符串存储为
String string1 = "Hello";
directly, then JVM creates a String object with the given price during a separate block of memory called String constant pool.
直接,然后 JVM 在称为 String 常量池的单独内存块中创建一个具有给定价格的 String 对象。
And whenever we have a tendency to try and produce another String as
每当我们倾向于尝试生成另一个字符串时
String string2 = "Hello";
JVM verifies whether or not any String object with constant price exists within the String constant pool, if so, rather than making a brand new object JVM assigns the reference of the existing object to the new variable.
JVM 验证 String 常量池中是否存在任何价格不变的 String 对象,如果存在,而不是创建一个全新的对象 JVM 将现有对象的引用分配给新变量。
And when we store String as
当我们将 String 存储为
String string = new String("Hello");
using the new keyword, a brand new object with the given price is made no matter the contents of the String constant pool.
使用 new 关键字,无论 String 常量池的内容如何,都会创建一个具有给定价格的全新对象。