我可以创建一个仅使用=
运算符实例化的类,就像String
类一样吗?或者这是Java中String
类特有的功能吗?
答案 0 :(得分:16)
No, you can't create a class that's instantiated just with =
operator because you can't overload an operator in Java like you can in C++ or C# (see Operator overloading in Java).
String
s are instantiated when you use "something"
only if it does not already exist in the memory, so you get a reference to the same exact String
object each time you write "something"
.
For example, if you do:
String a = "something";
String b = "something";
Then
a == b; // will be true.
You can take a look at this questions to learn more about how String
objects work:
答案 1 :(得分:14)
由于Java不支持用户定义的运算符重载,因此无法使用=
运算符创建新实例。
答案 2 :(得分:7)
代码String s = "Hello World!"
不会创建新的String
。它将字符串池中存在的String
引用分配给s
。如果字符串池中不存在String
,则会在字符串池中创建新的String
对象,但不能单独使用运算符=
。
这会创建新的String
objecs:
String s1 = new String("Hello World!"); // new Object
String s2 = new String("Hello World!"); // new Object
System.out.println(s1 == s2); // false
这可能会也可能不会在String Pool中创建一个新的String
对象:
String s1 = "Hello World!";
String s2 = "Hello World!";
System.out.println(s1 == s2); // true
使用getInstance()
模式可以非常接近上述行为,请考虑以下事项:
public class Singleton {
private Singleton(){}
private static class SingletonHelper{
private static final instance INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
}
然后你可以使用:
Singleton s = Singleton.getInstance();