JLabel 和 JTextField 字符串比较
当我使用 JLabel 字符串与 ==
进行比较时效果很好,
private JLabel someJLabel = new JLabel("some text");
...
System.out.println (someJLabel.getText() == "some text"); // returns true
但是当我使用 JTextField 时
private JTextField someJTextField = new JTextField("some text");
...
System.out.println (someJTextField.getText() == "some text"); // returns false
我知道如果我使用 someJTextField.getText().equals("some text");
它会工作得很好。
那么为什么它适用于 JLabel 但不适用于 JTextField
编辑:是的,我知道我应该将 .equals
与字符串一起使用,我已阅读这篇文章 http://javatechniques.com/blog/string-equality-and-interning/ 但已经知道我会使用“一些文本”,所以它可以引用相同的字符串对象
When I use JLabel string comparison with ==
works fine
private JLabel someJLabel = new JLabel("some text");
...
System.out.println (someJLabel.getText() == "some text"); // returns true
but when I use JTextField
private JTextField someJTextField = new JTextField("some text");
...
System.out.println (someJTextField.getText() == "some text"); // returns false
I know that if I used someJTextField.getText().equals("some text");
it would work fine.
So why it works with JLabel but not JTextField
EDIT: yes I know that I should use .equals
with string, I have read this article http://javatechniques.com/blog/string-equality-and-interning/ but it's known already that I will use "some text" so it could refer to same string object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它与 JTextField 和 JLabel 无关。
JVM 在内部使用字符串池,有时 == 运算符会起作用,因为不同的字符串(在您的例子中是“某些文本”)指向池中的相同字符串。
看看这里的问题
永远不要将字符串与 == 进行比较!
It's not related to JTextField and JLabel.
JVM uses String pool internally and sometimes == operator works because different strings (in your case "some text") points to the same string in pool.
Look at question here
Never compare strings with == !!!
JTextField 在内部将字符串复制到其可修改的文档对象以支持编辑,这样您就不会在 getText() 中返回相同的字符串。
JTextField internally copies the string to its modifiable document object to support editing so you don't get back the same string in getText().
将字符串与
.equals(Object obj)
进行比较==
主要应仅与原始对象一起使用。Compare Strings with
.equals(Object obj)
==
should mostly be used with only primitive objects.== 运算符和.equals 方法略有不同。
== 运算符比较两个对象,而 .equals 方法比较两个对象中的值。
在您的情况下,您正在比较两个不同的对象,尽管两者可能持有相同的值。根据您的情况,您可以使用 .equals 方法。这肯定会有所帮助!
There is a bit difference in == operator and.equals method.
== operator compares two objects while .equals method compare values in two object.
In your case you are comparing two different object although both may be holding same values. In your case you may use .equals method .This will definitely help!