How to compare 2 arrays in java

本文介绍了在Java中比较两个整型数组是否相等的方法,包括使用Arrays.equals()函数和直接通过引用比较的方式,并解释了为什么简单地使用引用比较不适用于数组的情况。
<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 same

For 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值