Comparing arrays that were saved as objects

A multipurpose field in an object of type ObjectHolder contains an obj object . obj can store a wrapped primitive or an array of primitives. How can we compare two obj s if they are arrays? A simplified example:

import java.util.Arrays;

public class ObjectHolder {

    public Object obj;

    public static void main(String[] args) {

        ObjectHolder oh1 = new ObjectHolder();
        oh1.obj = new int[]{ 3, 4, 5 };

        ObjectHolder oh2 = new ObjectHolder();
        oh2.obj = new int[]{ 3, 4, 5 };

        if (oh1.obj.getClass().isArray() && oh2.obj.getClass().isArray()) {
            System.out.println("We know both objects are arrays.");
            // System.out.println(Arrays.equals(oh1.obj, oh2.obj));
        }   
    }   

}   

The recorded line causes the compilation to abort.

Note. An array can be of any primitive type (or String), so just casting it in int [] is not a convenient general solution.

+4
source share
2 answers

Java Reflections ( Java):

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ObjectHolder {
    public Object obj;

    public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

        ObjectHolder oh1 = new ObjectHolder();
        oh1.obj = new int[] { 3, 4, 5 };

        ObjectHolder oh2 = new ObjectHolder();
        oh2.obj = new int[] { 3, 4, 6 };

        if (oh1.obj.getClass().isArray() && oh1.obj.getClass().equals(oh2.obj.getClass())) {
            Class<?> c = oh1.obj.getClass();

            if (!c.getComponentType().isPrimitive()) {
                c = Object[].class;
            }

            Method m = Arrays.class.getMethod("deepEquals", c, c);
            System.out.println((Boolean) m.invoke(null, oh1.obj, oh2.obj));
        }
    }
}

Update

, , @Andreas , , , Java Reflections:

if(oh1.obj.getClass().isArray() && oh1.obj.getClass().equals(oh2.obj.getClass())) {
    System.out.println(Arrays.deepEquals(new Object[] { oh1.obj }, new Object[] { oh2.obj }))
}
+2

, , getComponentType(), Arrays.equals() ( 9).

, Arrays.deepEquals(Object[] a1, Object[] a2), .

if (Arrays.deepEquals(new Object[] { oh1.obj }, new Object[] { oh2.obj })) {
    // They are equal, though they may not be arrays
}

javadoc, e1 = oh1.obj e2 = oh2.obj:

  • e1 e2 , Arrays.deepEquals(e1, e2) true
  • e1 e2 , Arrays.equals(e1, e2) true.
  • e1 == e2
  • e1.equals(e2) true.
+2

Source: https://habr.com/ru/post/1657668/


All Articles