java learning: java container --Set Interface Analysis

java container --Set Interface

Set the container does not contain duplicate values, in no particular order of data storage. Set the interface implementation class has HashSet, TreeSet. In addition LinkedHashSet inherited HashSet class.
(1) HashSet implementation class
underlying implemented using HashMap. The object is stored in the HashMap key value, the key may be utilized HashMap unrepeatable characteristics HashSet to ensure that no duplicate data object.
Following is a brief mock implementation of the principle of HashSet:

public class MyHashSet {
	HashMap map;
	private int size;
	private static final Object PRESENT = new Object();
	public MyHashSet(){
		map=new HashMap();
	}
	public int size(){
		return map.size();	
	}
	public void add(Object obj){
		map.put(obj, PRESENT);//set的不可重复其实就是利用了map里面键的不可重复	
	}
	public static void main(String[] args) {	
		MyHashSet  set =new MyHashSet();
		set.add("aaa");
		set.add(new String("aaa"));
		System.out.println(set.size());	
	}
}

(2) LinkedHashSet implementation class
LinkedHashSet inherited HashSet class, but is used LinkedHashSet LinkedHashMap, the order of elements in the LinkedHashSet is guaranteed, and the order that is traversed Map of the order of insertion is the same.

(. 3) implementation class TreeSet
TreeSet SortedSet also implements the interface. Underlying storage using a TreeMap, you can use it to extract an ordered sequence of elements from the Set must implement the Comparable interface otherwise sorted default dictionary.

It is seen from the above analysis, essentially based on Map Set implementation class implemented by Map Set as the key characteristic implement Set does not allow duplicate values.
Recommended: Java Learning: java container --Map interface (underlying implementation code to simulate a HashMap)

Published 57 original articles · won praise 13 · views 1122

Guess you like

Origin blog.csdn.net/weixin_42924812/article/details/105151593