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

/*

看一下部分的TreeSet源码....

public class TreeSet extends AbstractSet

implements NavigableSet, Cloneable, java.io.Serializable

{

private transient NavigableMap m;

//NavigableMap继承SortedMap, 二者都是接口,在TreeMap中有实现

private static final Object PRESENT = new Object();

TreeSet(NavigableMap m) {

this.m = m;

}

第一种构造方法

public TreeSet(Comparator super E> comparator) {

this(new TreeMap<>(comparator));

}

第二种构造方法

public TreeSet() {

this(new TreeMap());

}

..........

public boolean add(E e) {

return m.put(e, PRESENT)==null;

/*

再看一下 TreeMap 中是如何实现的 put()函数的

public V put(K key, V value) {

Entry 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 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 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 st = new TreeSet();

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 it = st.iterator(); it.hasNext();)

System.out.println(it.next());

}

}

class myClass implements Comparable{

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值