java中怎样判重_java中TreeSet集合如何实现元素的判重

1 /*

2 看一下部分的TreeSet源码....3 public class TreeSet extends AbstractSet4 implements NavigableSet, Cloneable, java.io.Serializable5 {6 private transient NavigableMap m;7 //NavigableMap继承SortedMap, 二者都是接口,在TreeMap中有实现8 private static final Object PRESENT = new Object();9

10 TreeSet(NavigableMap 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());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 t = root;29 if (t == null) {30 compare(key, key); // type (and possibly null) check31

32 root = new Entry<>(key, value, null);33 size = 1;34 modCount++;35 return null;36 }37 int cmp;38 Entry parent;39 // split comparator and comparable paths40 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 else50 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 else65 return t.setValue(value);66 } while (t != null);67 }68 Entry e = new Entry<>(key, value, parent);69 if (cmp < 0)70 parent.left = e;71 else72 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 classCompTest{90 public static voidmain(String args[]){91 Set st = new TreeSet();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 it =st.iterator(); it.hasNext();)98 System.out.println(it.next());99 }100 }101

102 class myClass implements Comparable{103

104 public intx;105 publicString name;106 public myClass(intx, String name){107 this.x=x;108 this.name=name;109 }110 public intcompareTo(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 publicString toString(){117 return x+" "+name;118 }119 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值