Java书写示例equals(),hashCode(),compareTo(),clone()等,不服来辩!~
equals()
实现equals()
参数必须是Object,而不能是外围类
覆盖equals()时,也要覆盖相应的hashCode(),与equals(),保持一致
另外注意String的默认值是null
public class Person {
private String name;
private int birthYear;
byte[] raw;
@Override
public boolean equals(Object o){
if(this == o){
return true;
}
if(!(o instanceof Person)){
return false;
}
Person other = (Person)o;
return StringUtils.equals(name, other.name)
&& birthYear == other.birthYear
&& Arrays.equals(raw, other.raw);
}
public static void main(String args[]){
Person p = new Person();
Person p2 = new Person();
System.out.println(p.equals(p2));
}
}
hashCode()
hashCode()最简单的合法实现就是简单地return 0;虽然这个实现是正确的,但是这会导致HashMap这些数据结构运行得很慢。
注意如果如果a或b未赋值会产生java.lang.NullPointerException
public class Person {
private String a;
private Object b;
private byte c;
int [] d;
@Override
public int hashCode(){
return a.hashCode() + b.hashCode() + c + Arrays.hashCode(d);
}public static void main(String[] args) {
Person p = new Person();
Person p1 = new Person();
HashMap map = Maps.newHashMap();
map.put(p,"hi");
map.put(p1,"hi2");
System.out.println(map);
System.out.println(map.get(p));
System.out.println(map.get(p1));
//System.out.println(p.hashCode());
}
}
CompareTo()
给出2条
public class Person implements Comparable{
private String firstName;
private String lastName;
private int birthdate;
@Override
public int compareTo(Person other){
int comparison = firstName.compareTo(other.firstName);
if(comparison == 0){
comparison = lastName.compareTo(other.lastName);
}
if(comparison == 0){
comparison = birthdate - other.birthdate;
}
return comparison;
}
}或者
public class Interval implements Comparable
{
private int start;
private int end;
@Override
public boolean equals(Object o) {
if (!(o instanceof Intervalable)) {
return false;
}
Intervalable other = (Intervalable)o;
return this.start == other.getStart() &&
this.end == other.getEnd();
}
@Override
public int hashCode() {
return this.start % 100 + this.end % 100;
}
@Override
public int compareTo(Object o) {
if (!(o instanceof Intervalable)) {
return -1;
}
Intervalable other = (Intervalable)o;
int comparison = this.start - other.getStart();
return comparison != 0 ? comparison : this.end - other.getEnd();
}
}
clone()
public class Values implements Cloneable {
private String abc;
private double foo;
private int[] bars;
private Date hired;
@Override
public Object clone() throws CloneNotSupportedException{
Values result = (Values)super.clone();
result.bars = result.bars.clone();
result.hired = (Date) result.hired.clone();
return result;
}
}