从内存中分配的用户获取的字符串值在哪里?
Scanner input = new Scanner(System.in);
String x = "hello"; // This is stored in String constant pool
String y = "hello";
String z = new String("hello"); // This is stored in normal heap
System.out.println("Enter "+x);
String u = input.next(); // Where is this stored?
System.out.println(x==y) // true because same memory address in SCP
System.out.println(x==z) // false because one is stored in SCP and other in heap
System.out.println(u==x) // false then not in SCP
System.out.println(u==z) // false then not in heap either
然后您将值存储在堆栈中吗?
我查看了OpenJdk8中的Scanner类,发现该字符串作为CharBuffer存储在Scanner类中。
public final class Scanner implements Iterator<String>, Closeable {
// Internal buffer used to hold input
private CharBuffer buf;
......
}
混淆是由于错误的假设(在代码的最后一行的注释中表示),即如果常量池未维护两个字符串(即“在堆上”),则它们是相同的宾语。它们实际上可能是不同的对象:
String s1 = new String("test");
String s2 = new String("test"); // s1 != s2
问题不在于是否分配了某个String
对象,而在于字符串是否由同一对象表示。