TreeSet排序方式(两种)

package collection;

import java.util.Comparator;
import java.util.TreeSet;

import java.util.Iterator;

public class TreeSetDemo {

 /**
  *   |--TreeSet:可以对Set集合中的元素进行排序(按自然顺序)
  *      底层数据结构是二叉树
  *      保证元素唯一性的依据:compareTo方法return 0;
  *
  * TreeSet排序的第一种方式:让院士自身具备比较性。元素需要实现compareTo接口,覆盖compareTo方法
  *               这种方式也叫做元素的自然顺序,或者叫做默认顺序
  * TreeSet排序的第二种方式:当元素自身不具备比较性时,或者具备的比较性不是所需要的。
  *               这时需要让集合自身具备比较性。
  *               在集合初始化时,就有了比较方式。
  *
  * 当两种排序方式都存在时,以比较器为主
  *
  * 定义一个类,实现comparator接口,覆盖compare方法。
  *         
  *     
  */
 public static void main(String[] args) {
  

  TreeSet ts = new TreeSet(new MyCompare());
  
  ts.add(new Student1("lisi02",22));
  ts.add(new Student1("lisi007",20));
  ts.add(new Student1("lisi007",29));
  ts.add(new Student1("lisi09",19));
  ts.add(new Student1("lisi08",18));
  //ts.add(new Student("lisi01",40));
  
  Iterator it = ts.iterator();
  
  while(it.hasNext()){
   Student1 stu = (Student1) it.next();
   sop(stu.getName()+"..."+stu.getAge());
  }
  

 }
 
 private static void sop(Object obj) {
  System.out.println(obj);
 }

}

class Student1 implements Comparable{
 private String name ;
 private int age;
 
 Student1(String name,int age){
  this.name = name;
  this.age = age;
 }
 
 public int compareTo(Object obj){
  if(!(obj instanceof Student1)){
   throw new RuntimeException("不是学生对象");
  }
  Student1 s = (Student1) obj;
  //System.out.println(this.name+"...compareTo.."+s.name);
  if(this.age>s.age)
   return 1;
  if(this.age==s.age){
   if(this.name.compareTo(s.name)>0)
    return 1;
   if(this.name.compareTo(s.name)<0)
    return -1;
   return 0;
  }
  else
   return -1;
 }

 public String getName() {
  return name;
 }

 public int getAge() {
  return age;
 }
}

class MyCompare implements Comparator{
 public int compare(Object o1, Object o2){
  Student1 s1 = (Student1) o1;
  Student1 s2 = (Student1) o2;
  
  int num =  s1.getName().compareTo(s2.getName());
  if(num == 0){
   //年龄排序方法1
   //return s1.getAge()-s2.getAge();
   /*
    *年龄排序方法2
   if(s1.getAge()>s2.getAge())
    return 1;
   if(s1.getAge()==s2.getAge())
    return 0;
   return -1;
   */
   //年龄排序方式3
   return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
   
  }
  return num;
  
 }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值