public class phone1 { int size = 1; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + size; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; phone1 other = (phone1) obj; if (size != other.size) return false; return true; } }
public class phone2 { int size = 1; }
public class PHONE { public static void main(String[] args) { // TODO Auto-generated method stub phone1 p1 = new phone1(); phone2 p2 = new phone2(); if(p1.equals(p2)) { System.out.println("两个电脑的参数相同!"); } else { System.out.println("两个电脑的参数不同!"); } } }
结果是 两个电脑的参数不同!
phone1 p1 = new phone1();
phone2 p2 = new phone2();
是分别用两个类指向了两个对象,equals的用法是用来比较同一个类的两个对象,所以你的main函数应该改成如下,你再去运行就是相同了
public class PHONE {
public static void main(String[] args) {
// TODO Auto-generated method stub
phone1 p1 = new phone1();
phone1 p2 = new phone1();
if(p1.equals(p2))
{
System.out.println("两个电脑的参数相同!");
}
else
{
System.out.println("两个电脑的参数不同!");
}
}
}
参数要toString,不然参数输出的是在内存中的地址,而不是参数的值
你这个只比较了对象,没有比较size诶,你看看把多余的代码注释掉看看