TreeSet的两种排序方法
来源:互联网 发布:手机大型网络枪战游戏 编辑:程序博客网 时间:2024/06/06 18:42
TreeSet的两种排序方法:自然排序和定义比较器,推荐使用定义比较器方法。
<span style="color:#333333;">import java.util.*;class treeset {public static void main(String[] args) {TreeSet t = new TreeSet();//TreeSet t = new TreeSet(new mycomparator());//第二种方法定义t.add(new student("a1",18));t.add(new student("a2",18));t.add(new student("a1",18));t.add(new student("a3",16));t.add(new student("a4",25));for(Iterator it = t.iterator();it.hasNext();){student s = (student)it.next();sop(s.getName()+","+s.getAge());}}public static void sop(Object obj){System.out.println(obj);}}/*自然排序法 定义Comparable接口,覆盖CompareTo方法*/class student implements Comparable{private String name;private int age;student(String name,int age){this.name = name;this.age = age;}public int compareTo(Object obj){if(!(obj instanceof student))throw new RuntimeException("不是学生");student s = (student)obj;if(this.age>s.age)return 1;if(this.age==s.age)return this.name.compareTo(s.name);return -1;}public String getName(){return name;}public int getAge(){return age;}}/*定义比较器 当两种方法都存在时,以比较器为主。定义一个类,实现Comparator接口,覆盖compare方法*/class mycomparator implements Comparator{public int compare(Object o1,Object o2){student s1 = (student)o1;student s2 = (student)o2;int num = s1.getName().compareTo(s2.getName());if(num ==0){if(s1.getAge()>s2.getAge())return 1;if(s1.getAge()==s2.getAge())return 0;return -1;}return num;}}</span>
1 0
- Treeset的两种排序方法
- Treeset的两种排序方法
- TreeSet的两种排序方法
- Treeset的两种排序方法
- Treeset的两种排序方法
- Java容器Treeset的两种排序方法
- TreeSet中自定义排序的两种方法
- TreeSet中的两种排序方法
- TreeSet的两种排序方式
- TreeSet的两种排序方式
- TreeSet集合的两种排序
- TreeSet的两种排序方式
- TreeSet的两种排序方式
- TreeSet的两种排序方式
- TreeSet的两种排序方式
- 自定义类的对象作为TreeSet元素的两种方法排序浅谈
- java自学笔记————对于TreeSet实现排序的两种方法;
- TreeSet的俩种排序方法
- Graph DataBase介绍
- 64位Linux编译cximage手记
- 排序算法
- SimHash
- 函数调用时堆栈的变化情况
- TreeSet的两种排序方法
- [leetcode] Rotate and Reverse
- iOS巅峰之Swift笔记详解(上)
- LeetCode 13:Roman to Integer
- Android layout布局属性、标签属性总结大全。
- Unity人工智能学习—高级随机运动
- Java 引用,栈 堆 的理解
- Java计算n-m之间质数/素数,打印出全部素数、总和以及个数
- java工具目录