TreeSet<Node> list = new TreeSet<>();Node n1 = new Node(1);Node n2 = new Node(2);Node n3 = new Node(3);Node n4 = new Node(4);Node n5 = new Node(5);
protected static class Node implements Comparable<Node>{public int id;private int __id;private static int ID = 1;public Node(int id) {this.id = id;this.__id = ID++;}@Overridepublic String toString() {return "Node("+__id+") "+id;}@Overridepublic int compareTo(Node o) {if(o.id>id)return 1;else if(o.id == id)return 0;elsereturn -1;}}
package examples.base;import java.util.TreeSet;public class TestTreeSet {public static void main(String[] args) {TreeSet<Node> list = new TreeSet<>();Node n1 = new Node(1);Node n2 = new Node(2);Node n3 = new Node(3);Node n4 = new Node(4);Node n5 = new Node(5);Node n = new Node(5);list.add(n1);list.add(n2);list.add(n3);list.add(n4);list.add(n5);list.add(n);System.out.println(list);System.out.println(list.higher(n3));n1.id = 5;if(list.remove(n1)){System.out.println("true");}list.add(n1);System.out.println(list);}protected static class Node implements Comparable<Node>{public int id;private int __id;private static int ID = 1;public Node(int id) {this.id = id;this.__id = ID++;}@Overridepublic String toString() {return "Node("+__id+") "+id;}@Overridepublic int compareTo(Node o) {if(o.id>id)return 1;else if(o.id == id)return 0;elsereturn -1;}}}
[Node(5) 5, Node(4) 4, Node(3) 3, Node(2) 2, Node(1) 1]Node(2) 2true[Node(1) 5, Node(4) 4, Node(3) 3, Node(2) 2, Node(1) 5]
原文:http://www.cnblogs.com/chzcb/p/3984681.html