Set:無序,元素不可重複(相對於元素的hashcode和equals來說)。
沒重寫hashCode()和hashCode()之前
在實體類中重寫相關方法
重寫後
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
map是指某個對象的鍵和值有映射關係。一個map對象不能包含重複的鍵,每個鍵至多映射一個值。(但是若干鍵可以映射到一些相同的值。)
This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.
Map接口替代了Dictionary類,Dictionary類是一個完全抽象類但卻不是接口。
The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.
Map接口提供了三種集合視圖(僅查看,Map本身不提供迭代器),允許map中的內容顯示爲set類型( keySet() )的鍵,collection類型的值( values() )或者set類型的鍵值對( entrySet() )。一些map的實現類,像TreeMap,可以對順序有特殊的設定(排序器)。另一些,像HashMap則沒有。
Map<Integer, Integer> tmap = new TreeMap<Integer,Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1); //按鍵值降序
//return o1.compareTo(o2); //按鍵值升序(默認)
}
});
A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value.
特別需要注意的是不允許把map本身作爲鍵,但是可以作爲值。(應用場景是什麼?)
Map可以存放Null值和Null鍵。
Map<Integer, Map<Integer, String> > map = new HashMap<Integer, Map<Integer, String>>();
TreeMap和HashMap都是非線程安全的
可以通過源碼中方法是否有synchronized關鍵字看出,當然文檔也有說明。
TreeMap:
HashMap:
HashTable線程安全
HashTable:
Ps:英語水平有限,望指正。