首页 > 编程语言 > 详细

Java TreeSet with Comparator sorting

时间:2016-05-06 02:12:46      阅读:95      评论:0      收藏:0      [点我收藏+]

TreeSet guarantees no duplicate data, also guarantees long(n) time complexity for add(), remove(), contains().

import java.util.Comparator;
import java.util.TreeSet;
 
public class MySetWithCompr {
 
    public static void main(String b[]){
         
        TreeSet<MyComp> ts = new TreeSet<MyComp>(new MyCompC());
        ts.add(new MyComp("RED", 1));
        System.out.println("added");
        ts.add(new MyComp("ORANGE", 1));
        System.out.println("added");
        ts.add(new MyComp("BLUE", 1));
        System.out.println("added");
        ts.add(new MyComp("GREEN", 1));
        System.out.println("added");
        ts.add(new MyComp("GREEN", 2));           
        System.out.println("green 2 added");
        for(MyComp a:ts) {
            System.out.println(a.name + " " + a.i);
        }
    }
}
 
class MyComp implements Comparable<MyComp> {
    public String name;
    public int i;

    public MyComp(String n, int x) {name = n; i = x;}

    @Override
    public int compareTo(MyComp entry) {
        if(name.equals(entry.name)) {
            System.out.println("local name = " + name);
            System.out.println("local i = " + i);
            System.out.println("entry name = " + entry.name);
            System.out.println("entry i = " + entry.i);
            entry.i = i; // update this as the duplicate data gets in
            System.out.println("local name = " + name);
            System.out.println("local i = " + i);
            System.out.println("entry name = " + entry.name);
            System.out.println("entry i = " + entry.i);
            return 0;
        }
        else {
            return name.equals(entry.name) ? -1 : 1;
        }
    }
}

class MyCompC implements Comparator<MyComp>{
 
    @Override
    public int compare(MyComp str1, MyComp str2) {
        return str1.compareTo(str2);
    }     
}

entry name = GREEN
entry i = 2
green 2 added
RED 1
ORANGE 1
BLUE 1
GREEN 2 (see, this value is updated)

Java TreeSet with Comparator sorting

原文:http://www.cnblogs.com/RuiYan/p/5463989.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!