gpt4 book ai didi

java - 大海捞针(用 .equals 比较两个对象时出错)

转载 作者:行者123 更新时间:2023-11-30 10:00:53 25 4
gpt4 key购买 nike

<分区>

试图找到一个字符串 "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 进行比较?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com