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

 /*
看一下部分的TreeSet源码....
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
{
private transient NavigableMap<E,Object> m;
//NavigableMap继承SortedMap, 二者都是接口,在TreeMap中有实现
private static final Object PRESENT = new Object(); TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
////第一种构造方法
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
////第二种构造方法
public TreeSet() {
this(new TreeMap<E,Object>());
}
..........
public boolean add(E e) {
return m.put(e, PRESENT)==null; /*
再看一下 TreeMap 中是如何实现的 put()函数的
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
*/
}
} 也就是说TreeSet内部实现使用TreeMap这个类来完成的
TreeSet的内部实现元素之间是否相等?
如果指定了Comparator(也就是利用第一种构造方法), 那么就用其中的compare方法进行比较
否则就用Comparable中的compareTo()方法进行元素的比较
*/ import java.util.*;
public class CompTest{
public static void main(String args[]){
Set<myClass> st = new TreeSet<myClass>();
st.add(new myClass(1, "fd"));
st.add(new myClass(2, "fff"));
st.add(new myClass(2, "tttt"));
st.add(new myClass(1, "fd")); for(Iterator<myClass> it = st.iterator(); it.hasNext();)
System.out.println(it.next());
}
} class myClass implements Comparable<myClass>{ public int x;
public String name;
public myClass(int x, String name){
this.x=x;
this.name=name;
}
public int compareTo(myClass tmp){
if(this.x==tmp.x)
return this.name.compareTo(tmp.name);
else return this.x-tmp.x;
} public String toString(){
return x+" "+name;
}
}
上一篇:Spark分布式执行原理


下一篇:【Android的从零单排开发日记】之入门篇(十一)——Android的Intent机制