object
除基本数据类型外,java所有对象都继承自Object对象,一下介绍几种Object具有的方法,一般自定义对象需重写以下方法。
一、equals()方法
重写方法步骤建议:
1 //显式参数命名为otherObject,增加@override注解,防止public boolean equals(Person other)实现成多态 2 public boolean equals(Object otherObject){ 3 //检查是否引用同一对象 4 if(this==otherObject) return true; 5 //检查是否为null 6 if(otherObject == null) return false; 7 //检查是否属于同一个类 8 if(getClass()!=otherObject.getClass()) return false; 9 //otherObject转换成相应的类类型变量 10 ClassName other = (ClassName) otherObject; 11 //一次比较具体的域,先判断每个域是否为空,Objects.equals(a,b)方法都为null,返回true,一个参数null返回false,都不为null,调用a.equals(b) 12 return field1 == other.field1 13 &&Objects.equals(field2,other.field2)
设计原则:
1、自反性:任何非空x, x.equals(x)返回true。
2、对称性:x.equals(y) 返回true,则y.equals(x) 也返回true。
3、传递性:x.equals(y) 返回true,y.equals(z) 返回true,x.equals(z)也应该返回true。
4、一致性:x ,y 对象未发生变化,则x.equals(y) 返回结果不变。
5、非空x,x.equals(null),应返回false。
二、hashCode()方法
Object类默认hashcode值为对象存储地址。重写equals方法,同时必须重写hashcode方法,如果x.equals(y) 返回true,则x y hashCode必须相同。
//String类hashCode public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
仅作为笔记使用,记录信息过于简洁。