我是一个学习Java的C++人.我正在阅读Effective Java,有些事让我很困惑.它说从不写这样的代码:
String s = new String("silly");
Run Code Online (Sandbox Code Playgroud)
因为它会创建不必要的String对象 但相反它应该写成这样:
String s = "No longer silly";
Run Code Online (Sandbox Code Playgroud)
好吧到目前为止......但是,鉴于这个课:
public final class CaseInsensitiveString {
private String s;
public CaseInsensitiveString(String s) {
if (s == null) {
throw new NullPointerException();
}
this.s = s;
}
:
:
}
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
String s = "polish";
Run Code Online (Sandbox Code Playgroud)
为什么第一个陈述好吗?不应该
CaseInsensitiveString cis = "Polish";
我如何使CaseInsensitiveString行为String如此上述声明是可以的(有和没有扩展String)?它是什么让它能够传递像这样的文字?根据我的理解,Java中没有"复制构造函数"概念?
我有以下代码行来比较String.str1不等于str2,这是可以理解的,因为它比较了对象引用.但那么为什么s1等于s2?
String s1 = "abc";
String s2 = "abc";
String str1 = new String("abc");
String str2 = new String("abc");
if (s1==s2)
System.out.println("s1==s2");
else
System.out.println("s1!=s2");
if (str1==str2)
System.out.println("str1==str2");
else
System.out.println("str1!=str2");
if (s1==str1)
System.out.println("str1==s1");
else
System.out.println("str1!=s1");
Run Code Online (Sandbox Code Playgroud)
输出:
s1==s2
str1!=str2
str1!=s1
Run Code Online (Sandbox Code Playgroud) String str = new String("Hello");
Run Code Online (Sandbox Code Playgroud)
通常我在互联网上的许多文章中都读到,当我们编写上述语句时,会创建两个对象.在堆上创建一个String对象,并在Literal Pool上创建一个字符串对象.并且堆对象也引用在Literal Pool上创建的对象.(如果错误,请更正我的陈述.)
请注意,上面的解释是根据我的理解,阅读了一些互联网上的文章.
所以我的问题是..是否有任何方法可以停止在文字池中创建字符串对象.怎么做?
[请告诉我有关理解此文字池的最佳链接,如何实施]
String在以下代码段中创建了多少个不同的对象实例?
String s1 = new String("hello");
String s2 = "GoodBye";
String s3 = s1;
Run Code Online (Sandbox Code Playgroud)
我不确定这里的所有推理.
通过使用new从String类创建实例的关键字,我猜这必须是一个对象.但是,我很困惑,是String在new现在考虑了一个方法,因为它有()然后它调用String文字"你好"吗?
String s2 = "Goodbye";
我认为这是一个字符串文字,因为字符串实际上是对象,所以即使字符串文字被认为是对象.不是100%确定是否属实.
String s3 = s1;只是回到s1.因此,它并不明显.
所以我的答案是2个不同的对象.
请解释我是对还是错.