Java TreeSet with Comparator sorting

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");
        System.out.println(ts.add(new MyComp("GREEN", 2)));           
        System.out.println("green 2 added");
        for(MyComp a:ts) {
            System.out.println(a.name + " " + a.i);
        }
        System.out.println("remove:" + ts.remove(new MyComp("GREEN",0))); // returns true, the nice thing is that you can remove items according to its feature.
        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;
            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);
    }
     
}

 

local name = RED
local i = 1
entry name = RED
entry i = 1
local name = RED
local i = 1
entry name = RED
entry i = 1
added
added
added
added
local name = GREEN
local i = 2
entry name = GREEN
entry i = 1
local name = GREEN
local i = 2
entry name = GREEN
entry i = 2
false
green 2 added
RED 1
ORANGE 1
BLUE 1
GREEN 2 (see this value has been updated)
local name = GREEN
local i = 0
entry name = GREEN
entry i = 2
local name = GREEN
local i = 0
entry name = GREEN
entry i = 0
remove:true (remove successfully, you can remove based on "GREEN", not ("GREEN", 2). sometimes you don't know what's the value associated with GREEN, but you know you need to delete "GREEN", then you use this to achieve that.)
RED 1
ORANGE 1
BLUE 1

posted @ 2016-05-06 01:26  Rui Yan  阅读(247)  评论(0编辑  收藏  举报