【发布时间】:2020-01-07 19:49:28
【问题描述】:
试图在 Object 数组中查找字符串 "needle"。但是使用.equals 进行比较会给我一个错误。但是使用== 可以。为什么?
我以为我必须使用.equals 来比较对象/字符串。
以== 运行的代码
public class ANeedleInTheHaystack_8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Object[] haystack2 = {"283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle", "something somebody lost a while ago"};
Object[] haystack1 = {"3", "123124234", null, "needle", "world", "hay", 2, "3", true, false};
System.out.println(findNeedle(haystack2));
System.out.println(findNeedle(haystack1));
}
public static String findNeedle(Object[] haystack) {
for(int i = 0 ; i < haystack.length ; i ++) {
if(haystack[i] == "needle") {
return String.format("found the needle at position %s", i);
}
}
return null;
}
}
输出
found the needle at position 5
found the needle at position 3
以及不使用.equals 运行的代码
public class ANeedleInTheHaystack_8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Object[] haystack2 = { "283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle",
"something somebody lost a while ago" };
Object[] haystack1 = { "3", "123124234", null, "needle", "world", "hay", 2, "3", true, false };
System.out.println(findNeedle(haystack2));
System.out.println(findNeedle(haystack1));
}
public static String findNeedle(Object[] haystack) {
for(int i = 0 ; i < haystack.length ; i ++) {
if(haystack[i].equals("needle")) {
return String.format("found the needle at position %s", i);
}
}
return null;
}
}
输出
found the needle at position 5
Exception in thread "main" java.lang.NullPointerException
at ANeedleInTheHaystack_8.findNeedle(ANeedleInTheHaystack_8.java:15)
at ANeedleInTheHaystack_8.main(ANeedleInTheHaystack_8.java:10)
似乎我只在与null 比较时遇到错误。 .equals 可以将对象与null 进行比较吗?
【问题讨论】:
-
.equals只能在您知道调用对象不为空的情况下使用。您可以通过切换到"needle".equals(haystack[i])使其在您的代码中工作,因为"needle"显然总是非空 -
改用
Objects.equals。它将优雅地处理null值。
标签: java