Java Array Comparison

前端 未结 6 1890
名媛妹妹
名媛妹妹 2021-01-04 19:48

Working within Java, let\'s say I have two objects that, thanks to obj.getClass().isArray(), I know are both arrays. Let\'s further say that I want to compare

6条回答
  •  孤独总比滥情好
    2021-01-04 20:13

    you can use the enum strategy pattern to create a comparator for each type:

    public enum ArrayEq {
        BYTE_PRIMITIVE(Byte.TYPE) {
            protected boolean doEquals(Object array1, Object array2) {
                return Arrays.equals((byte[]) array1, (byte[]) array2);
            }
        },
        ... enum element for each component type
    
       private final Class type;
    
       private ArrayEq(final Class type) { this.type = type; }
       public Class getComponentType() { return type; }
    
       // force all enums to implement this method
       protected abstract boolean doEquals(Object array1, Object array2);
    
       public static boolean equals(Object array1, Object array2) {
           if(array1 == null) return array2 == null;
    
           // you need to populate this map in a static initializer of the enum
           // a simple linear search would work too since the number of elements is small
           typeToElementMap.get(array1.getComponentType())
               .doEquals(array1, array2);
       }
    

    }

    Error handling omitted, but of course, you want to throw IllegalArgumentException wherever incorrect types are passed around (I prefer to let ClassCastException be JVM generated, and throw IAE in my own code when I detect something wrong).

提交回复
热议问题