字符串池可以包含两个具有相同值的字符串吗? [英] Can string pool contain two strings with the same value?

查看:178
本文介绍了字符串池可以包含两个具有相同值的字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串池是否包含两个具有相同值的字符串?

Can string pool contain two strings with the same value??

String str = "abc";
String str1 = new String("abc");

   Will the second statement with `new()` operator creates two objects of `string` "abc", one on `heap` and another on `string` pool? 

   Now if i call intern() on str1 ie str1.intern(); as a third statement, will str1 refer to the "abc" from String pool? 

  If yes then what will happen to the object that was created on heap earlier by the new(). Will that object be eligible for garbage collection.?
  If no then what will be the result of str1.intern();?


推荐答案

首先也不会创建一个对象,也会创建第二个对象将只创建一个字符串对象。区别在于第一个将在String池中创建,第二个将仅在堆中创建。
如果您将调用 str1.intern(); ,则会将其添加到字符串池中。

No first will also create one object and also second one will create only one string object. Difference is that first one will create in String pool and second one will create in heap only. If you will call str1.intern(); then it will be added to String pool.

String str1 = "abc";
String str2 = new String("abc");
Stirng str3 = "abc"

这里将创建两个对象。第一行将使用引用str1创建一个强对象,第三行将指向在第一行中使用引用str3创建的同一对象,但在第二行中将创建一个新对象,因为我们使用 new 这里是关键字。希望它能帮到你。

Here two objects will be created. first line will create one strong object with reference str1 and 3rd line will point to the same object created in 1st line with reference str3 but in 2nd line one new object will be created as we are using new keyword here. Hope it will help you.

同时检查这个答案。那里有很好的解释。

Also check this answer. Good explanation is there.

这篇关于字符串池可以包含两个具有相同值的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆