- import java.util.*;
- /*
- 需求:TreeSet集合两种存入元素的方法
- */
- class TreeSetTest
- {
- public static void main(String[] args)
- {
- TreeSet ts=new TreeSet(new Mycompare());
- ts.add(new Student("张三",29));
- ts.add(new Student("李四",29));
- ts.add(new Student("王五",31));
- ts.add(new Student("张三",29));
- ts.add(new Student("赵六",30));
- ts.add(new Student("李四",29));
- sop(ts);
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
- //第一种:让需要存入 TreeSet集合的元素实现Comparable,从而具备比较性
- class Student implements Comparable
- {
- private String name;
- private int age;
- Student(String name,int age){
- this.name=name;
- this.age=age;
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- //复写compareTo()方法,定义元素的比较方式
- public int compareTo(Object obj){
- if(!(obj instanceof Student))
- throw new RuntimeException("数据类型不符");
- Student stu=(Student)obj;
- int num=this.name.compareTo(stu.name);
- if(num==0)
- return new Integer(this.age).compareTo(stu.age);
- return num;
- }
- //自定义equals方法,判断两个Person对象是否相同
- public boolean equals(Object obj){
- if(!(obj instanceof Student))
- return false;
- Student stu=(Student)obj;
- return this.getName().equals(stu.getName())&&this.age==stu.age;
- }
- public String toString(){
- return this.name+":"+this.age;
- }
- }
- //第二种方式:自定义比较器,将比较器对象传给TreeSet集合对象,使集合具备对元素的比较功能
- class Mycompare implements Comparator
- {
- public int compare(Object obj1,Object obj2){
- Student stu1=(Student)obj1;
- Student stu2=(Student)obj2;
- int num=new Integer(stu1.getAge()).compareTo(stu2.getAge());
- if(num==0)
- return stu1.getName().compareTo(stu2.getName());
- return num;
- }
- }
复制代码
|
|