示例程序
import com.google.common.base.Objects;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import java.util.Comparator;
/**
* @author Kevin
* @description
* @date 2016/8/4
*/
public class ObjectTest {
public static void main(String[] args) {
Student student = new Student("Han", 1, 80);
Student student1 = new Student("Kevin", 28, 99);
Student student2 = new Student("Chris", 27, 90);
Student student3 = new Student("Herry", 30, 80);
System.out.println("==========equals===========");
// false
System.out.println(student.equals(student2));
// false
System.out.println(student.equals(student1));
// false
System.out.println(student.equals(student3));
System.out.println("==========hashCode===========");
System.out.println(student.hashCode());
System.out.println(student1.hashCode());
System.out.println(student3.hashCode());
System.out.println(student2.hashCode());
System.out.println("==========toString===========");
System.out.println(student.toString());
System.out.println(student1.toString());
System.out.println(student2.toString());
System.out.println(student3.toString());
System.out.println("==========compareTo===========");
System.out.println(student.compareTo(student1));
System.out.println(student.compareTo(student2));
System.out.println(student2.compareTo(student1));
System.out.println(student2.compareTo(student));
}
}
class Student implements Comparable<Student> {
public String name;
public int age;
public int score;
Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int hashCode() {
return Objects.hashCode(name, age);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student that = (Student) obj;
return Objects.equal(name, that.name)
&& Objects.equal(age, that.age)
&& Objects.equal(score, that.score);
}
return false;
}
@Override
public String toString() {
// addValue(val); add("key","val"); 打印出的效果就差参数名
return Objects.toStringHelper(this)
.addValue(name)
.addValue(age)
.addValue(score)
.add("paramName","paramValue")
.toString();
}
@Override
public int compareTo(Student other) {
// ComparisonChain是一个lazy的比较过程, 当比较结果为0的时候,
// 即相等的时候, 会继续比较下去, 出现非0的情况, 就会忽略后面的比较
return ComparisonChain.start()
.compare(name, other.name)
.compare(age, other.age)
.compare(score, other.score, Ordering.natural().nullsLast())
.result();
}
}
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return ComparisonChain.start()
.compare(s1.name, s2.name)
.compare(s1.age, s2.age)
.compare(s1.score, s2.score)
.result();
}
}