<pre name="code" class="java">// we need to import java.util.Arrays to use Arrays.equals().
import java.util.Arrays;
class Test
{
public static void main (String[] args)
{
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (Arrays.equals(arr1, arr2))
System.out.println("Same");
else
System.out.println("Not same");
}
}
Output:
Same
"Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the
two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order"
To compare:
1, Either use for loops to compare them two, given that their sizes are same.
2, Or use:
class Test
{
public static void main (String[] args)
{
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
if (arr1 == arr2) // Same as arr1.equals(arr2)
System.out.println("Same");
else
System.out.println("Not same");
}
}
Output: Not sameFor the same reason, we cannot use hashSet to remove duplicates:
public static void main(String[] args) {
HashSet<int[]> rest = new HashSet<int[]>();
int[] a = {1,2};
int[] b = {1,2};
rest.add(a);
rest.add(b);
rest.add(a);
for(int[] x: rest){
System.out.print(x[0]+" "+x[1]);
System.out.println();
}
}
Output:
1 2
1 2
本文介绍了在Java中比较两个整型数组是否相等的方法,包括使用Arrays.equals()函数和直接通过引用比较的方式,并解释了为什么简单地使用引用比较不适用于数组的情况。

1238

被折叠的 条评论
为什么被折叠?



