sansamh

导航

通过HashSet达到对象集去重的实现(jdk1.8)

通过HashSet达到对象集去重的实现(jdk1.8)

public class Contract {

    private String contractId;
    private String contractName;

    private Date begin;
    private Date end;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Contract contract = (Contract) o;
        //自己的判断条件是时间段重合的算做同一个对象
        return false;
    }

    @Override
    public int hashCode() {
    	//通过Objects类提供的hash方法
        int hash = Objects.hash(contractId, contractName);
        return hash;
    }
public class Test {

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        Contract c1 = new Contract();
        c1.setContractName("c");
        c1.setContractId("1");

        c1.setBegin(calendar.getTime());
        calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);
        c1.setEnd(calendar.getTime());
        /*                  */
        Contract c2 = new Contract();
        c2.setContractName("c");
        c2.setContractId("1");

        calendar.setTime(new Date());
        c2.setBegin(calendar.getTime());
        calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+2);
        c2.setEnd(calendar.getTime());

        HashSet<Contract> set = new HashSet<>();
        set.add(c1);
        set.add(c2);
        System.out.println(set.size());
    }
}
1.HashSet内部维护类了一个HashMap,可以看到默认的构造方法其实就是实例化了一个hashMap
 private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }

    /**
     * Constructs a new set containing the elements in the specified
     * collection.  The <tt>HashMap</tt> is created with default load factor
     * (0.75) and an initial capacity sufficient to contain the elements in
     * the specified collection.
     *
     * @param c the collection whose elements are to be placed into this set
     * @throws NullPointerException if the specified collection is null
     */
    public HashSet(Collection<? extends E> c) {
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }
2.在添加对象的时候判断了对象是否的hashCode是否相等,如果相等需要进一步判断对象的equals方法
 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

posted on 2018-05-11 15:42  sansamh  阅读(1620)  评论(0编辑  收藏  举报