首页 > 代码库 > Java中Arrays类的两个方法:deepEquals和equals

Java中Arrays类的两个方法:deepEquals和equals

deepEquals和equals是Java中Arrays类的两个静态方法,可是它们之间有什么样的区别呢?

代码一、

import java.util.Arrays;

public class Test {
	public static void main(String[] args) {
		String[][] name1 = {{ "G","a","o" },{ "H","u","a","n"},{ "j","i","e"}};
		String[][] name2 = {{ "G","a","o" },{ "H","u","a","n"},{ "j","i","e"}};

		System.out.println(Arrays.equals(name1, name2));    // false
		System.out.println(Arrays.deepEquals(name1, name2));// true
	}
}
代码二、
import java.util.Arrays;

public class Test {
	public static void main(String[] args) {
		String[] name1 = {"G","a","o","H","u","a","n","j","i","e"};
		String[] name2 = {"G","a","o","H","u","a","n","j","i","e"};
		System.out.println(Arrays.equals(name1, name2));      // true
		System.out.println(Arrays.deepEquals(name1, name2));  // true
	}
}
总结:

        1、deepEquals用于判定两个指定数组彼此是否深层相等,此方法适用于任意深度的嵌套数组。

        2、equals用于判定两个数组是否相等,如果两个数组以相同顺序包含相同元素,则返回true,否则返回false。

        3、通过比对“代码一”和“代码二”我们可以得出这样一个结论:如果两个数组使用equals返回true,则使用deepEquals也返回true,也就是说在比较的两个数组均为一维数组的前提下,equals和deepEquals的比较结果没有差别;

        4、如果要比较多为数组,则需要使用deepEquals方法;

Java中Arrays类的两个方法:deepEquals和equals