集合是數據存儲中,重要的容器對象。
單列集合
- Collection 單例集合根接口
- List 實現了List接口的集合類 特點: 有序,可重復
- ArrayList 實現了List接口 底層使用數組 特點:速度快,增刪慢
- LinkedList 底層使用鏈表數據結構, 特點: 查詢速度慢,增刪快
- Vector 底層使用數組 特點:對比ArrayList線程安全,效率低
- Set 實現了Set接口的集合類 特點: 無序, 不可重復
- HashSet 底層使用Hash表實現, 特點: 存取速度快
- TreeSet 底層使用二叉樹實現 特點: 排序存儲
- List 實現了List接口的集合類 特點: 有序,可重復
<pre>注意: HashSet <h6>1.HashSet先調用HashCode方法算出Hash值,對比Hash值.相同進行第二步,建議重寫HashCode方法
</h6><h6>2.調用對象的Equals方法,建議重寫Equals方法</h6>
</pre>
<pre>注意:TreeSet<h6>1.元素具備自然排序的特點,就按照自然順序進行排序</h6><h6>2.如果元素不具備自然排序的特點,那么元素需要實現Comparable接口,自定義比較規則,重寫CompareTo方法</h6></pre>
雙列集合
- Map 鍵值對存儲 鍵不可重復,值可重復
- HashMap 底層哈希表
- TreeMap 底層二叉樹
ArrayList Demo
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<String>();
array.add("First");
array.add("Second");
array.add("Three");
for (int i = 0; i < array.size(); i++) {
System.out.println(array.get(i));
}
}
Console
First
Second
Three
HashSet Demo
public static void main(String[] args) {
HashSet<String> hSet = new HashSet<>();
hSet.add("First");
hSet.add("Second");
hSet.add("Three");
// Iterator 遍歷
Iterator<String> it = hSet.iterator();
while(it.hasNext()){
System.out.print(it.next() + ",");
}
}
// 注意 :while中不能直接修改元素個數
Console
Second,First,Three,
HashMap Demo
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<>();
map.put("Fisrt", 1);
map.put("Second",2);
map.put("Three", 3);
Set<Entry<String,Integer>> entrys= map.entrySet();
// 遍歷
for (Entry<String, Integer> entry : entrys) {
System.out.println("Key :" + entry.getKey() + "Value :" + entry.getValue());
}
}
Console
Key :SecondValue :2
Key :FisrtValue :1
Key :ThreeValue :3
給個github follow me的鏈接,上面有很多初學者可供學習的資料,項目.
<a>https://github.com/SuperZee</a>