Treeset的两种排序方法
来源:互联网 发布:网络写作软件哪个好 编辑:程序博客网 时间:2024/06/03 18:56
- 转自:<a href="http://luochuang724.blog.163.com/blog/static/203606212201222821045518/">http://luochuang724.blog.163.com/blog/static/203606212201222821045518/</a>
- Treeset 的自定义的两种排序方式
-
- 第一种:在元素中定义排序规则。元素自身具有比较性实现Comparable接口 覆盖compareTo方法
- import java.util.Iterator;
- import java.util.TreeSet;
-
-
-
-
-
-
-
-
- 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 {
-
- 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);
- }
-
-
- return -1;
-
- }
-
- public String toString()
- {
- return age+" = "+"name"+name;
- }
- }
-
- 第二种:在集合中定义排序 实现Comparator接口 覆盖compare方法。
-
- TreeSet(Comparator<? super E> comparator)
- 构造一个新的空 TreeSet,它根据指定比较器进行排序。
-
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeSet;
-
- 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());
- }
- }
0 0