码迷,mamicode.com
首页 > 编程语言 > 详细

Java TreeSet with Comparator sorting

时间:2016-05-06 02:15:17      阅读:202      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!