Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 其中是来自Scanner类的字符串值';是否在内存中分配了s.next()方法?_Java_Memory Management_Java.util.scanner - Fatal编程技术网

Java 其中是来自Scanner类的字符串值';是否在内存中分配了s.next()方法?

Java 其中是来自Scanner类的字符串值';是否在内存中分配了s.next()方法?,java,memory-management,java.util.scanner,Java,Memory Management,Java.util.scanner,其中是从内存中用户分配的字符串值 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 = in

其中是从内存中用户分配的字符串值

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

那么值u是否存储在堆栈中?

我查看了中的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
问题不在于是否分配了某个
字符串
对象,而在于to字符串是否由同一个对象表示


另请参见

System.out.println(u==z)//false那么也不在堆中
您为什么这么认为?它仍然在堆上,但不在SCP中。仅仅因为两个对象都存储在堆中并不能使它们成为相同的对象,这就是==正在检查的。您认为
新字符串(“hello”)==新字符串(“hello”)
的结果应该是什么?为什么?@RedwanHossainArnob“u的字符串值在堆中”不是真的。堆中有一个字符串对象由变量
u
指向。该对象有一个值。堆中有一个由变量
z
指向的不同字符串对象。它与由
u
标识的对象具有相同的值,但它们不是相同的对象。相等运算符(
==
)比较对象标识,而不是对象内容。这就是为什么当我们关心对象的值是否相等时,我们使用
.equals()
来比较对象。@RedwanHossainArnob让我问一个反问题,为什么您认为它应该返回
true