Collection:Set集合

Collection集合中,除了List集合之外,還有Set集合。Set也是一個接口,使用Set需要實現它,它的常見實現類有HashSet、TreeSet。以常用的HashSet舉例。

HashSet:

HashSet實現Set接口,底層以HashMap實現,不保證Set的迭代順序,即Set是無序不重複的。這兒有一個細節需要注意:HashSet無序可以理解,但是TreeSet是有序的,爲什麼說Set是無序的呢?這兒有必要對有序這個詞進行理解一下。

我們一般說的有序,是指,進入集合的順序,先加入集合的元素,將先取到。使用迭代器迭代時,是依次去取元素。而TreeSet的有序,是指按自然順序或者某種規則去排序,用迭代器對它進行迭代時,它取出的數據並不是先加入的先取到,後加入的後取到,而是根據他排序後的順序去取。所以,可以說Set它是無序的。

HashSet常用的方法和List差不多。主要看一下Set的底層實現原理。

    public HashSet() {
        map = new HashMap<>();
    }
這是HashSet的構造器,可以看到,它是用HashMap去實現的。爲什麼HashSet會是無序不重複的呢,先看看它的add()方法:

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
private static final Object PRESENT = new Object();
根據構造器可以看到map是一個HashMap,所以map.put(e, PRESENT)是在HashMap中添加一個元素,它是把對象e作爲Map的key,把object作爲Map的value,因爲Map的鍵是不重複的,所以HashSet會保證添加的元素是不重複的。

上面說到HashSet是無序且不重複的,但是存儲一個對象會不會可以重複呢?用個例子來看一下:

public class Student {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Student() {
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}
public class HashSetDemo {
	public static void main(String[] args) {
		Set<Student> set = new HashSet<Student>();
		set.add(new Student("lizy", 23));
		set.add(new Student("liyn", 21));
		set.add(new Student("lizy", 23));
		for (Student student : set) {
			System.out.println(student);
		}
	}
}
運行結果:

Student [name=lizy, age=23]
Student [name=liyn, age=21]
Student [name=lizy, age=23]
上面可以看到,HashSet在添加對象的時候,添加了重複的對象,爲什麼會重複呢?上面看了它的源碼,它底層是以Map來實現的,所以,它的具體操作,要去HashMap中去查看。下面是HashMap的源碼:

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

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;
    }

上面HashMap源碼,在後期Map中,再詳細解釋。上面代碼大概可以看出,當傳入一個對象時,它並不是將對象的值作爲主鍵添加在Map中,而是使用了hashCode()這個方法。它是將對象取hash值,然後做主鍵的,而在set中添加對象時,每次都是new一個新的對象,所以它們的地址是不同的,因此它們的hash值也是不同的,那麼怎麼保證它相等呢?

要解決這個,先看影響它的是什麼,由源碼大概可以看出,要添加一個元素,前面有很多條件,其中hashCode和equals大概可以知道,這兩個條件是影響的關鍵。而hashCode和equals都是Object方法,重寫它,如果添加的對象的值完全相同,則返回同一個值:

<span style="white-space:pre">	</span>@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
在Student中添加這兩個方法,即可解決值全部相同的對象,不被加入到Set集合中。

除了HashSet之外,還有一個TreeSet。TreeSet,它根據自然順序或者某些指定的條件進行對元素進行排序。TreeSet有兩個構造器,一個是無參構造器,另一個是帶一個接口的比較器構造器。無參構造器主要以自然順序去排序。帶參構造器,是根基指定的條件去排序。先看看TreeSet的底層實現:

    public TreeSet() {
        this(new TreeMap<E,Object>());
    }
    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }
    public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }
根據上面的構造器可以看到,它的底層是以TreeMap來實現的。它的添加方法具體實現代碼如下:

    public V put(K key, V value) {
        Entry<K,V> t = root;<span style="white-space:pre">						</span>//建立根節點
        if (t == null) {
            compare(key, key); // type (and possibly null) check<span style="white-space:pre">	</span>

            root = new Entry<>(key, value, null);<span style="white-space:pre">			</span>//第一次添加數據,將其放入根結點
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;<span style="white-space:pre">				</span>//如果存在參數
        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);<span style="white-space:pre">				</span>//比較兩個大小
                if (cmp < 0)
                    t = t.left;<span style="white-space:pre">						</span>//小於的,放入左孩子
                else if (cmp > 0)
                    t = t.right;<span style="white-space:pre">					</span>//大於的,放入右孩子
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {<span style="white-space:pre">								</span>//下面不存在參數的,原理和他一樣
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                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實現底層代碼,根據這兩個構造器,做一個簡單實例:

無參構造器案例:

public class TreeSetDemo {
	public static void main(String[] args) {
		TreeSet<Integer> ts = new TreeSet<Integer>();
		ts.add(11);
		ts.add(23);
		ts.add(13);
		ts.add(14);
		ts.add(50);
		for (Integer integer : ts) {
			System.out.print(integer+" ");
		}
	}
}

輸出結果:11 13 14 23 50 

帶比較器參數構造器案例:

public class TreeSetDemo {
	public static void main(String[] args) {
		TreeSet<Integer> ts = new TreeSet<Integer>(new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {
				//倒序排序
				return -o1.compareTo(o2);
			}
		});
		ts.add(11);
		ts.add(23);
		ts.add(13);
		ts.add(14);
		ts.add(50);
		for (Integer integer : ts) {
			System.out.print(integer+" ");
		}
	}
}
輸出結果:50 23 14 13 11 

上面是TreeSet的底層實現,Tree的實現,可能不是很好理解,下一篇我將把二叉樹的構建和三種遍歷方式用代碼去實現,再回頭看它底層實現源碼就會熟悉很多。













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章