Java Array Comparison

前端 未结 6 1841
名媛妹妹
名媛妹妹 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:34

    You can use the getClass() method without isArray(); check out this example:

    byte[] foo = { 1, 2 };
    byte[] bar = { 1, 2 };
    
    System.out.println(foo.getClass());
    System.out.println(bar.getClass());
    
    if(foo.getClass() == bar.getClass())
        System.out.println(Arrays.equals(foo, bar));
    

    I admit up front that this is far from a perfect solution. It shortens the potentially huge if-else chain that you had in the original post, but causes errors if the types are not the same. The following similar code wouldn't even compile in MyEclipse 8.0:

    byte[] obj1 = { 1, 2 };
    String[] obj2 = { "1", "2" };
    
    System.out.println(obj1.getClass());
    System.out.println(obj2.getClass());
    
    if(obj1.getClass().toString().equals(obj2.getClass().toString()))
        System.out.println(Arrays.equals(obj1, obj2));
    

    IF you are confident that you won't have type mismatches and your only problem is that you don't want to figure out which type you have, this could work.

提交回复
热议问题