首页 > 代码库 > HashSet中实现不插入重复的元素

HashSet中实现不插入重复的元素

/*看一下部分的HashSet源码....public class HashSet<E>    extends AbstractSet<E>    implements Set<E>, Cloneable, java.io.Serializable{    static final long serialVersionUID = -5024744406713321676L;    private transient HashMap<E,Object> map;    private static final Object PRESENT = new Object();    public HashSet() {        map = new HashMap<>();    }    public HashSet(Collection<? extends E> c) {        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));        addAll(c);    }    public HashSet(int initialCapacity, float loadFactor) {        map = new HashMap<>(initialCapacity, loadFactor);    }    public HashSet(int initialCapacity) {        map = new HashMap<>(initialCapacity);    }    HashSet(int initialCapacity, float loadFactor, boolean dummy) {        map = new LinkedHashMap<>(initialCapacity, loadFactor);    }    public Iterator<E> iterator() {        return map.keySet().iterator();    }    public boolean add(E e) {        return map.put(e, PRESENT)==null;//在下面的代码中我们可以看见map.put()的代码    }}public class HashMap<K,V>    extends AbstractMap<K,V>    implements Map<K,V>, Cloneable, Serializable{     .....     final int hash(Object k) {        int h = 0;        if (useAltHashing) {            if (k instanceof String) {                return sun.misc.Hashing.stringHash32((String) k);            }            h = hashSeed;        }        h ^= k.hashCode();//调用了改对象中的hashCode()方法,由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数        h ^= (h >>> 20) ^ (h >>> 12);        return h ^ (h >>> 7) ^ (h >>> 4);    }     public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key);//调用了上面的函数        int i = indexFor(hash, table.length);        for (Entry<K,V> e = table[i]; e != null; e = e.next) {            Object k;            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {                V oldValue = http://www.mamicode.com/e.value;"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{   public int x;   public String name;   public myClass(int x, String name){       this.x=x;       this.name=name;   }   public int hashCode(){      return x;   }   public boolean equals(Object tmp){//这里是方法的重写,参数的类型和个数一定要一样....       return x==((myClass)tmp).x && name.equals( ((myClass)tmp).name);   }   public String toString(){      return x+" "+name;   }}