Java-Arrays类-deepEquals()和equals()详解

deepEquals和equals是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  
    }  
}  
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方法;

posted on 2017-11-04 17:12  小左流年  阅读(1029)  评论(0编辑  收藏  举报

导航