且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中比较int数组?

更新时间:2022-06-21 23:55:58

此处需要注意的几件事:

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年以前),您必须比较两个数组的每个元素对.如今,您可以只使用静态的
  • == 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.)