抱歉,现在已经很晚了,所以我可能不会解释所有的细节,但是我一直在努力解决这个问题,我无法理解为什么数组中的对象Item对象引用不使用Item类的equals方法得到了。我检查了函数内部两个Item对象的类类型,并返回类Item。
import java.util.Arrays;
class Item{
private int data;
Item(int data){
this.data=data;
}
public boolean equals(Item item){
return data==item.data;
}
public String toString(){
return String.format("{data: %d}", data);
}
}
public class Problem3{
public static void main(String[] args){
Object object=new Object(){ public String toString(){return String.format("{hash code: %d}", hashCode());} };
String date="Friday, July 29";
Item item=new Item(2);
Object[] array={"Fri, Jul 29", new Item(2), object, new Integer[]{212, 220, 240, 313, 316, 320, 323, 331}, new Double[]{Math.E, Math.PI, 9.80665}, new Boolean[]{true, true, true, true}, new String[]{"Eckhart", "Eric", "Owen", "Chris", "David", "Mark"}};
System.out.println(Arrays.deepToString(array));
System.out.println();
System.out.println("Searching array for entries . . .");
System.out.printf("\"%s\": %b\n", date, isMember(array, date));
System.out.printf("%s: %b\n", item, isMember(array, item));
System.out.printf("%s: %b\n", object, isMember(array, object));
System.out.print("[\u0065, \u03c0, \u0047]: "+isMember(array, new Double[]{Math.E, Math.PI, 9.80665})); //\ud835 \u0065
}
private static boolean isMember(Object[] array, Object value){
if(array.length>0){
Object member=array[array.length-1];
if(member instanceof Object[] && value instanceof Object[]){
if(Arrays.deepEquals((Object[])member, (Object[])value)){
return true;
}
}
else if(member.getClass().equals(Item.class) && value.getClass().equals(Item.class)){
if(member.equals(value)){
return true;
}
}
else if(member.equals(value)){ //Object parameter does not have field "data" of Item equals method, so "instance of Item" applied above
return true;
}
Object[] arrayNext=Arrays.copyOf(array, array.length-1);
return isMember(arrayNext, value);
}
return false;
}
}
答案 0 :(得分:1)
equals
方法的签名错误,因此不会覆盖Object.equals
方法。它应该是
public boolean equals(Object item)
答案 1 :(得分:1)
您不会从Object类重写equals。看这里: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
public boolean equals(Object obj)
要覆盖Java中的方法,您必须使用相同的方法签名。您的参数是Item而不是Object。
答案 2 :(得分:1)
等于方法的签名应该是
public boolean equals(Object obj)