Java KeyEvent - 为什么 "Unknown" != "Unknown"?

Java KeyEvent - why "Unknown" != "Unknown"?

为什么

KeyEvent.getKeyText(0).substring(0, 7) == "Unknown"

return 当

时为假
System.out.print(KeyEvent.getKeyText(0).substring(0, 7));

准确地打印 "Unknown"?

在Java中字符串是对象,所以你不应该与==比较。您必须在字符串上调用 equals 才能比较那里的内容。 如果您将它们与 == 进行比较,则您通过参考来比较它们。

KeyEvent.getKeyText(0).substring(0, 7).equals("Unknown");

另一种选择是包含:

KeyEvent.getKeyText(0).contains("Unknown");

看到这个post:Java String.equals versus ==