JAVA - 判断数组相等

java.util.Arrays类的equals()方法

* 类加载

import java.util.Arrays;

* 判断一维数组元素相等的方法

static boolean equals(type[] a, type[] b): 如果两个数则大小相同并且下标相同的元素都对应相等,返回true

int[] ary = {1,2,3,4,5,6};
int[] ary1 = {1,2,3,4,5,6};
int[] ary2 = {1,2,3,4};
System.out.println("数组ary是否与数组ary1相等? :" + Arrays.equals(ary, ary1));
System.out.println("数组ary是否与数组ary2相等? :" + Arrays.equals(ary, ary2));

注:equals()方法判断数组元素相等的方法:对于基本数据类型,直接判断对应元素的值是否相等;对于引用数据类型,根据该类的equals()方法来判断对应元素是否相等

import java.util.Arrays;

class Student{
	private String s;
	private int a;
	
	public Student(String s, int a) {
		this.s = s;
		this.a = a;
	}
}

public class Test {
	public static void main(String[] args){
        Student s1 = new Student("zhangsan", 19);
        Student s2 = new Student("lisi", 20);
        Student [] array1 = {new Student("zhangsan", 19), s2}; 
        Student [] array2 = {s1, s2};  
        Student [] array3 = {s1, s2};  
        System.out.println(Arrays.equals(array1, array2));
        System.out.println(Arrays.equals(array3, array2));
    }
}
import java.util.Arrays;

class Student{
	private String s;
	private int a;
	
	public Student(String s, int a) {
		this.s = s;
		this.a = a;
	}
	
	@Override  
    public boolean equals(Object obj) {  
        if (obj instanceof Student) {  
        	Student c = (Student) obj;  
            return a == c.a;  
        }  
        return false;  
    } 
}

public class Test {
	public static void main(String[] args){
        Student s1 = new Student("zhangsan", 19);
        Student s2 = new Student("lisi", 20);
        Student [] array1 = {new Student("zhangsan", 19), s2}; 
        Student [] array2 = {new Student("zhangsan", 19), s2};  
        System.out.println(Arrays.equals(array1, array2));
    }
}

* 判断多维数组元素相等的方法

static boolean deepEquals(type[] a, type[] b)

int[][] ary1 = {{1,2}, {3,4,5}, {6}};
int[][] ary2 = {{1,2}, {3,4,5}, {6}};
System.out.println("数组ary1是否与数组ary2相等? :" + Arrays.deepEquals(ary1, ary2));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值