Phone.java
public class Phone implements Comparable{
private int age;
private String name;
public Phone(){
}
public Phone(String name,int age){
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Phone{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
System.out.println("Phone equals...");
if (this == o) return true; // 判断对象是否是同一个
if (o == null || getClass() != o.getClass()) return false;
Phone phone = (Phone) o;
return age == phone.age &&
Objects.equals(name, phone.name);
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
@Override
public int compareTo(Object o) {
if(o instanceof Phone){
Phone phone = (Phone)o;
int compare = this.name.compareTo(phone.name);
if(compare != 0){
return compare;
}else{
return this.age - phone.age;
}
}else{
throw new RuntimeException("输入的类型不匹配");
}
}
}
TestTreeSet.java
public class TestTreeSet {
// 自然排序
@Test
public void test1(){
TreeSet ts = new TreeSet();
/* ts.add(45);
ts.add(-8);
ts.add(95);
ts.add(0);*/
ts.add(new Phone("Tom",15));
ts.add(new Phone("Jack",15));
ts.add(new Phone("Bob",15));
ts.add(new Phone("Jerry",15));
ts.add(new Phone("Tom",23));
Iterator iterator = ts.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
// 定制排序。
@Test
public void test2(){
Comparator com = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Phone && o2 instanceof Phone){
Phone p1 = (Phone)o1;
Phone p2 = (Phone)o2;
int compareP = p1.getName().compareTo(p2.getName());
if(compareP != 0){
return compareP;
}else{
return Integer.compare(p1.getAge(),p2.getAge());
}
}else{
throw new RuntimeException("输入的数据类型不匹配");
}
}
};
TreeSet ts = new TreeSet(com);
ts.add(new Phone("Tom",15));
ts.add(new Phone("Jack",15));
ts.add(new Phone("Bob",15));
ts.add(new Phone("Jerry",15));
ts.add(new Phone("Tom",23));
Iterator iterator = ts.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}