如何在Java中比较int数组

如何在Java中比较int数组

本文介绍了如何在Java中比较int数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试比较两个int数组时,即使它们完全相同, if(一个==两个)中的代码仍然无法执行.为什么是这样?

When I am trying to compare two int array, even though they are exactly the same, the code inside if (one == two) still doesn't get executed. Why is this?

Object[] one = {1,2,3,4,5,6,7,8,9};
Object[] two = {1,2,3,4,5,6,7,8,9};

if (one == two){
    System.out.println("equal");
} else {
    System.out.println("not equal");
}

推荐答案

此处需要注意的几件事:

A few things to note here:

  • == 比较引用而不是值...也就是说,您要问的是这两个数组是否是相同的确切实例,而不是它们是否包含相同的值.
  • 您正在使用 == 的事实意味着您可能不了解 equals() 方法.com/javase/8/docs/api/java/lang/Object.html"rel =" nofollow> Object .这不是解决当前问题所需的方法,但请注意,通常,当比较两个对象的值时,应使用 obj1.equals(obj2),而不是 obj1 == obj2 .现在 == 可以使用 int 之类的原语(例如普通的 x == 3 等),所以也许这就是您使用它的原因,但我只是想确保您了解 equals() == .
  • 在过去(1998年以前),您必须比较两个数组的每个元素对.如今,您可以只使用静态的 java.util.Arrays 类.对于所有原始类型(在每个元素对的内部使用 == )和 Object (其中肯定会使用 equals()(每对).
  • == compares the references, not the values . . . that is, you are asking whether these two arrays are the same exact instance, not whether they contain the same values.
  • The fact that you are using == means you may not know about the equals() method on Object. This is not the method you'll need to solve this current problem, but just be aware that in general, when you compare the values of two objects, you should be using obj1.equals(obj2), not obj1 == obj2. Now == does work with primitives like int (e.g. plain old x == 3 and so on), so maybe that's why you were using it, but I just wanted to make sure you were aware of equals() vs. ==.
  • In the old old days (pre-1998), you would have to compare each element pair of the two arrays. Nowadays, you can just use that static Arrays.equals() method on the java.util.Arrays class. This method is overloaded for all the primitive types (using == under the hood for each element pair) and for Object (where it will most definitely use equals() for each pair.)

这篇关于如何在Java中比较int数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:22