【问题标题】:Comparing arrays using .equals使用 .equals 比较数组
【发布时间】:2014-08-07 09:47:36
【问题描述】:

我正在尝试比较两个对象,它们在每个字段上都有完全相同的值。

System.out.println(basicTypes1);

[id=2013756475,
boolean2={true},
byte2={32},
short2={1,2},
int2={10,11},
float2={0.1,0.2},
double2={0.01,0.02},
number2={10,11},
char2={c,t},
string2={7c2cfc4e-5805-45ad-8687-4f2412a92e1d,d91b9609-39fb-4fe9-9f36-db33608970d1},
date2={Tue Jun 17 11:48:56 BST 2014,Tue Jun 17 11:48:56 BST 2014},
obj2={443f38f4-d5b4-41fb-aeeb-d086f4edc62a,d855d031-ad8d-4fce-b5e1-d959034a0b7c}]

System.out.println(basicTypes2);

[id=2013756475,
boolean2={true},
byte2={32},
short2={1,2},
int2={10,11},
float2={0.1,0.2},
double2={0.01,0.02},
number2={10,11},
char2={c,t},
string2={7c2cfc4e-5805-45ad-8687-4f2412a92e1d,d91b9609-39fb-4fe9-9f36-db33608970d1},
date2={Tue Jun 17 11:48:56 BST 2014,Tue Jun 17 11:48:56 BST 2014},
obj2={443f38f4-d5b4-41fb-aeeb-d086f4edc62a,d855d031-ad8d-4fce-b5e1-d959034a0b7c}]

请注意,它们都打印相同的结果。

但是,当我使用 .equals 比较 number2 和 string2 每个对象中的字段时,返回值为 false。

以下是比较值的方法示例:

public boolean isEqual(Object basicTypes1, Object basicTypes2) {
boolean objectResult = true, fieldResult;

        Class<?> leftClass = basicTypes1.getClass();
        Class<?> rightClass = basicTypes2.getClass();

        List<Field> fields = getAllFields(leftClass);

        for (Field field : fields) {
            field.setAccessible(true);
        //the fields number2 and string2 enter in this if so I won't post the rest of them
        if (TypeVerifier.isBasicType(field.getType())) { // handle primitives
            fieldResult = leftFieldValue.equals(rightFieldValue); //comparing the above values, returns false, why?
            if (!fieldResult) {
                logger.error(getFieldError(leftClass, field, leftFieldValue, rightFieldValue));
            }

        }
     objectResult = objectResult && fieldResult;
    }
return obejctResult;
}

还有什么其他方法可以比较Number[] number2 和String[] string2? 所有其他字段在相同的 equals 方法中返回 true(如预期的那样)。

number2={10,11} 和 string2={7c2cfc4e-5805-45ad-8687-4f2412a92e1d,d91b9609-39fb-4fe9-9f36-db33608970d1}

谢谢

【问题讨论】:

  • 我做到了,但我无法删除它,因为我也需要它来比较非数组值。为什么只在 Number[] 和 String[] 中失败?
  • 可能只和原始数组有关

标签: java comparison equals


【解决方案1】:

equals() 将比较两个对象的引用,因此除了原语和包装类之外,默认情况下您总是在比较两个不同的对象。

这种机制背后的原因是开发者可以重写根类 Object 的 equals 方法,以根据对象的内容决定何时返回 true 表示相等。为所有可能存在的类创建一个 equals() 函数是不可能的,也不合理的。在这种情况下,在 Objects 中创建 equals 方法的标准是检查两者的引用。

数字和字符串不是原语,因此您正在比较不同对象的引用,因此您会得到一个 false bool 作为返回。

查看此链接以获取完整内容:http://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html

【讨论】:

    【解决方案2】:

    你可以试试

    for(int i=0;i<basicTypes1.string2.length;i++)
    {
       fieldResult=basicTypes1.string2[i].equals(basicTypes2.string2[i]);
    }  
    

    numbers2 也一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多