标签:
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