【发布时间】: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