java中TreeSet集合如何实现元素的判重
生活随笔
收集整理的這篇文章主要介紹了
java中TreeSet集合如何实现元素的判重
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 /*
2 看一下部分的TreeSet源碼....
3 public class TreeSet<E> extends AbstractSet<E>
4 implements NavigableSet<E>, Cloneable, java.io.Serializable
5 {
6 private transient NavigableMap<E,Object> m;
7 //NavigableMap繼承SortedMap, 二者都是接口,在TreeMap中有實現
8 private static final Object PRESENT = new Object();
9
10 TreeSet(NavigableMap<E,Object> m) {
11 this.m = m;
12 }
13 第一種構造方法
14 public TreeSet(Comparator<? super E> comparator) {
15 this(new TreeMap<>(comparator));
16 }
17 第二種構造方法
18 public TreeSet() {
19 this(new TreeMap<E,Object>());
20 }
21 ..........
22 public boolean add(E e) {
23 return m.put(e, PRESENT)==null;
24
25 /*
26 再看一下 TreeMap 中是如何實現的 put()函數的
27 public V put(K key, V value) {
28 Entry<K,V> t = root;
29 if (t == null) {
30 compare(key, key); // type (and possibly null) check
31
32 root = new Entry<>(key, value, null);
33 size = 1;
34 modCount++;
35 return null;
36 }
37 int cmp;
38 Entry<K,V> parent;
39 // split comparator and comparable paths
40 Comparator<? super K> cpr = comparator;
41 if (cpr != null) {
42 do {
43 parent = t;
44 cmp = cpr.compare(key, t.key);
45 if (cmp < 0)
46 t = t.left;
47 else if (cmp > 0)
48 t = t.right;
49 else
50 return t.setValue(value);
51 } while (t != null);
52 }
53 else {
54 if (key == null)
55 throw new NullPointerException();
56 Comparable<? super K> k = (Comparable<? super K>) key;
57 do {
58 parent = t;
59 cmp = k.compareTo(t.key);
60 if (cmp < 0)
61 t = t.left;
62 else if (cmp > 0)
63 t = t.right;
64 else
65 return t.setValue(value);
66 } while (t != null);
67 }
68 Entry<K,V> e = new Entry<>(key, value, parent);
69 if (cmp < 0)
70 parent.left = e;
71 else
72 parent.right = e;
73 fixAfterInsertion(e);
74 size++;
75 modCount++;
76 return null;
77 }
78 */
79 }
80 }
81
82 也就是說TreeSet內部實現使用TreeMap這個類來完成的
83 TreeSet的內部實現元素之間是否相等?
84 如果指定了Comparator(也就是利用第一種構造方法), 那么就用其中的compare方法進行比較
85 否則就用Comparable中的compareTo()方法進行元素的比較
86 */
87
88 import java.util.*;
89 public class CompTest{
90 public static void main(String args[]){
91 Set<myClass> st = new TreeSet<myClass>();
92 st.add(new myClass(1, "fd"));
93 st.add(new myClass(2, "fff"));
94 st.add(new myClass(2, "tttt"));
95 st.add(new myClass(1, "fd"));
96
97 for(Iterator<myClass> it = st.iterator(); it.hasNext();)
98 System.out.println(it.next());
99 }
100 }
101
102 class myClass implements Comparable<myClass>{
103
104 public int x;
105 public String name;
106 public myClass(int x, String name){
107 this.x=x;
108 this.name=name;
109 }
110 public int compareTo(myClass tmp){
111 if(this.x==tmp.x)
112 return this.name.compareTo(tmp.name);
113 else return this.x-tmp.x;
114 }
115
116 public String toString(){
117 return x+" "+name;
118 }
119 }
?
轉載于:https://www.cnblogs.com/hujunzheng/p/3814902.html
總結
以上是生活随笔為你收集整理的java中TreeSet集合如何实现元素的判重的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡副卡要不要激活
- 下一篇: 人民币钯金是什么东西