【Java学习笔记】<集合框架>TreeSet,Comparable,Comparator

时间:2021-08-20 10:30:06
 public class Person implements Comparable{
private String name;
private int age; public Person(){
super();
}
public Person(String name, int age)
{
super();
this.name = name;
this.age = age;
} @Override
public int hashCode() { return name.hashCode()+age*27;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Person))
throw new ClassCastException("类型错误"); Person p = (Person) obj; return this.name.equals(p.name) && this.age == p.age;
}
@Override
public String toString() { return name+":"+age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Object o) { //先按年龄排,再按姓名排 Person p = (Person)o; int temp = this.age - p.age; return temp==0? this.name.compareTo(p.name):temp; } }
 import java.util.Comparator;

 import cn.itcast.p1.bean.Person;

 public class ComparatorByName implements Comparator {    //先按姓名排,再按年龄排

     @Override
public int compare(Object o1, Object o2) {
Person p1 = (Person)o1;
Person p2 = (Person)o2; int temp = p1.getName().compareTo(p2.getName()); return temp==0?p1.getAge()-p2.getAge() : temp;
} }
 import java.util.Iterator;
import java.util.TreeSet; import cn.itcast.p1.bean.Person;
import cn.itcast.p5.comparator.ComparatorByName; public class TreeSetDemo { public static void main(String[] args) {
// demo1();
TreeSet ts = new TreeSet(new ComparatorByName()); //添加 new ComparatorByName(),会出现结果一,去除的话 ,出现结果2
//Comparator 优先于 Comparable ts.add(new Person("zhangsan",28));
ts.add(new Person("lisi",21));
ts.add(new Person("zhouqi",29));
ts.add(new Person("zhaoliu",25));
ts.add(new Person("wangwu",24));
ts.add(new Person("lisi",21));
ts.add(new Person("zhouqi",29)); Iterator it = ts.iterator(); while (it.hasNext())
{
Person p = (Person)it.next(); System.out.println(p);
} } public static void demo1() {
TreeSet ts = new TreeSet(); ts.add("abc");
ts.add("zaa");
ts.add("aa");
ts.add("nba");
ts.add("cba"); Iterator it = ts.iterator(); while (it.hasNext())
{
System.out.println(it.next());
}
} }

【Java学习笔记】<集合框架>TreeSet,Comparable,Comparator

【Java学习笔记】<集合框架>TreeSet,Comparable,Comparator