Java 如何比较数组中的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/700748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare value in array?
提问by Jessy
how to compare value in an array?
如何比较数组中的值?
I have array named list which contains 12 elements. I see if value in index 0 is equal or not equal to value in index 2.
我有一个名为 list 的数组,其中包含 12 个元素。我查看索引 0 中的值是否等于或不等于索引 2 中的值。
I have tried this code but it doesnt seems to work.
我试过这段代码,但它似乎不起作用。
if ((list.get(0)==list.get(2) && list.get(1)==list.get(3))
{
System.out.println("equal")
}
采纳答案by Kevin Crowell
if(list[0] == list[2] && list[1] == list[3]){
System.out.println("equal");
}
If they are strings:
如果它们是字符串:
if(list[0].equals(list[2]) && list[1].equals(list[3])){
System.out.println("equal");
}
回答by Jon Skeet
If it's reallyan array, you want:
如果它真的是一个数组,你想要:
if (list[0] == list[2] && list[1] == list[3])
Note that if the array is of reference types, that's comparing by reference identity rather than for equality. You might want:
请注意,如果数组是引用类型,则是通过引用标识而不是相等进行比较。你可能想要:
if (list[0].equals(list[2])) && list[1].equals(list[3]))
Although that will then go bang if any of the values is null. You might want a helper method to cope with this:
尽管如果任何值为空,那将会爆炸。您可能需要一个辅助方法来解决这个问题:
public static objectsEqual(Object o1, Object o2)
{
if (o1 == o2)
{
return true;
}
if (o1 == null || o2 == null)
{
return false;
}
return o1.equals(o2);
}
Then:
然后:
if (objectsEqual(list[0], list[2]) && objectsEqual(list[1], list[3]))
If you've really got an ArrayList
instead of an array then all of the above still holds, just using list.get(x)
instead of list[x]
in each place.
如果你真的有一个ArrayList
代替数组,那么以上所有内容仍然成立,只是在每个地方使用list.get(x)
代替list[x]
。
回答by unwind
You are comparing object references, not objects themselves. You need to use a method call. All classes inherit equals()
from the root Object
class, so it might work:
您正在比较对象引用,而不是对象本身。您需要使用方法调用。所有类都继承equals()
自根Object
类,因此它可能有效:
if(list.get(0).equals(list.get(2)) && list.get(1).equals(list.get(3)))
{
System.out.println("equal");
}
This articleseems to be a good summary of other comparison methods available.
这篇文章似乎很好地总结了其他可用的比较方法。