Set

JAVA中的set有三种:HashSet,TreeSet和LinkedHashSet。

①HashSet的输出顺序是不确定的,但是它的速度最快;

②TreeSet输出顺序是升序排列的;

③LinkedHashSet输出顺序是确定的,就是插入时的顺序。

HashSet

package com.sjp.list;

import java.io.Serializable;
import java.util.HashMap;

/**
 * Created by Timor on 2019/6/24.
 */
public class MyHashSet<E> implements Serializable {

    private static final long serialVersionUID = 394734015309173362L;

    private transient HashMap<E,Object> map;

    private static final Object PRESENT = new Object();

    public MyHashSet() {
        map = new HashMap<E, Object>();
    }

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
}

TreeSet

package com.sjp.list;

import java.io.Serializable;
import java.util.HashMap;
import java.util.TreeMap;

/**
 * Created by Timor on 2019/6/24.
 */
public class MyTreeSet<E> implements Serializable {

    private static final long serialVersionUID = 394734015309173362L;

    private transient TreeMap<E,Object> map;

    private static final Object PRESENT = new Object();

    public MyTreeSet() {
        map = new TreeMap<E, Object>();
    }

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
}

 

posted @ 2019-06-24 17:17  骚皮皮  阅读(379)  评论(0编辑  收藏  举报