首页 > 学院 > 开发设计 > 正文

TreeSet的定制排序

2019-11-06 06:14:02
字体:
来源:转载
供稿:网友

方式1:在元素自身中定义排序规则

需要元素自身实现Comparable接口

/*** *TreeSet是一个有序集合,TreeSet中元素将按照升序排列,缺省是按照 自然顺序进行排列,意味着TreeSet中元素要实现Comparable接口。 我们可以在构造TreeSet对象时,传递实现了Comparator接口的比较器对象。 注意排序時:當主要的條件相同時,判斷次要條件。 * @author Administrator * */public class TreeSetTest { public static void main(String[] args) { TreeSet treeset = new TreeSet();//定义一个集合 treeset.add(new person2(10, "liuyia")); treeset.add(new person2(10, "liuyib")); treeset.add(new person2(15, "liuyi34")); treeset.add(new person2(11, "liuyi4")); treeset.add(new person2(12, "liuyi4")); Iterator itera = treeset.iterator(); while (itera.hasNext()) { System.out.PRintln(itera.next()); } }}class person2 implements Comparable {//实现Comparable 接口 private int age; private String name; 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; } public person2(int age, String name) { this.age = age; this.name = name; } public int compareTo(Object o) { if(!(o instanceof person2)) throw new RuntimeException("对象类型不一致!"); person2 p = (person2)o; if(this.age>p.age){ return -1; } if(this.age<p.age){ return 1; } if(this.age==p.age){ return this.name.compareTo(p.name);//當主要的條件也就是age的值相同時時候此時判斷次要條件姓名 } return -1; } //打印结果 public String toString(){ return age+" = "+"name"+name; }}

方式2(传给集合一个自定义排序器)

写个实现Comparble接口的排序器

public class TreeSetTest { public static void main(String[] args) { //定义一个集合,并将自定义的排序器传给集合。这样该集合就会使用我们定义的排序规则来排序 TreeSet treeset = new TreeSet( new mycomp()); treeset.add(new person2(10, "liuyia")); treeset.add(new person2(10, "liuyib")); treeset.add(new person2(15, "liuyi34")); treeset.add(new person2(11, "liuyi4")); treeset.add(new person2(12, "liuyi4")); Iterator itera = treeset.iterator(); while (itera.hasNext()) { System.out.println(itera.next()); } }}class person2 { private int age; private String name; 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; } public person2(int age, String name) { this.age = age; this.name = name; } public String toString(){ return age+" = "+"name"+name; }}class mycomp implements Comparator{ public int compare(Object o1, Object o2) { person2 p1 = (person2)o1; person2 p2 = (person2)o2; return -(p1.getAge()- p2.getAge()); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表