Object所有类的根类
equals hashCode toString getClass 都可以覆写自定义
equals 判断两个对象是否相等
Person p1 = new Person();
Person p2 = new Person();
Person p3 = p1;
System.out.print(p1==p2) //false
System.out.print(p1.equals(p2)) //false
System.out.print(p1.equals(p3)) //true
每个类都可以覆盖equals,定义自己的逻辑
public class TestObject extends Object {
int id;
String name;
public TestObject(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestObject other = (TestObject) obj;
if (id != other.id)
return false;
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestObject object1 = new TestObject(1000,"旺财");
TestObject object2 = new TestObject(1000, "小强");
System.out.println(object1==object2);
System.out.println(object1.equals(object2));
String string = "123";
System.out.println(string.equals("123"));
}
}
hasCode 类的哈希值
//覆盖hasCode函数
public int hasCode(){
return age;
}
public class Object_demo1 {
private int age;
public Object_demo1(int age) {
this.age = age;
}
public boolean equals(Object o){
Object_demo1 od = (Object_demo1)o;
return this.age == od.age;
}
public int hashCode(){
return this.age;
}
}
Object_demo1 od = new Object_demo1(20);
Object_demo1 od1 = new Object_demo1(20);
System.out.println(od.equals(od1));
System.out.println(od.hasCode());
System.out.println(od);
System.out.println(od.hashCode());
System.out.println(Integer.toHexString(od.hashCode()));
//未覆盖hashCode
//com.company.Object_demo1@2cfb4a64
//754666084
//2cfb4a64
//已覆盖hashCode
//com.company.Object_demo1@14
//20
//14
toString
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
getClass
System.out.println(od.getClass() == od1.getClass()); //true
System.out.println(od.getClass().getName());
//com.company.Object_demo1