我今天换了讲师,他说我用了一个奇怪的代码.(他说最好使用.equals,当我问为什么时,他回答"因为它是!")
所以这是一个例子:
if (o1.equals(o2))
{
System.out.println("Both integer objects are the same");
}
Run Code Online (Sandbox Code Playgroud)
而不是我习惯的:
if (o1 == o2)
{
System.out.println("Both integer objects are the same");
}
Run Code Online (Sandbox Code Playgroud)
这两者之间有什么区别.为什么他的方式(使用.equals)更好?
通过快速搜索找到了这个,但我无法理解这个答案:
何时应该将Strings作为对象进行比较,何时应该使用他们的equals方法?为了确保,我总是使用equals,但这似乎不是很有效.在什么情况下我可以确定string1 == string2使用安全?
谢谢!