1、概念說明
區別:數組固定長度的,集合,數組的長度是可以變化的。
List,繼承Collection,可重復、有序的對象
Set,繼承Collection,不可重復、無序的對象
Map,鍵值對,提供key到value的映射。key無序、唯一;value無序,可重復
2、集合類結構圖
3、集合特性比較
線程安全的效率都比較低,Vector,已被淘汰,可使用ArrayList替代。Hashtable,已被淘汰,可使用HashMap替代,如果是高並發的線程安全的實現,推薦使用ConcurrentHashMap。
4、接口和方法
Collection的常見方法:
(1)添加
boolean add(E o); (6)修改:set(index,elementt) (7)查詢:get(index),indexof(obj)
(2)刪除
boolean remove(Object o);
boolean removeAll(Collection<? extends E> c)
void clear();
(3)判斷
a.判斷集合中是否有元素:boolean isEmpty();
b.判斷集合中是否包含某個元素:boolean contains(Object o);
c.判斷集合中是否包含某些元素:boolean contains(Collection<?> c);
(4)獲取
a.獲取集合中元素個數:int size();
b.遍歷集合中所有元素(迭代器):Iterator<E> iterator();
c.判斷兩個集合中是否存在相同的元素並保留兩個集合中相同的元素刪除不同的元素:boolean retainAll(Collection<?> c);
(5)其他
將集合中元素轉為數組: Ojbect[] toArray();
Map的接口方法:1、增加:put(key,value),putall(map) 2、刪除:clear(),remove(key)3、判斷:isEmpty(),containValue(),containsKey(), 4、查詢:get(key),size(),entrySet(),keySet()
5、集合遍歷
list遍歷
import java.util.*; public class Test{ public static void main(String[] args) { List<String> list=new ArrayList<String>(); list.add("Hello"); list.add("World"); list.add("HAHAHAHA"); //第一種遍歷方法使用foreach遍歷List for (String str : list) { //也可以改寫for(int i=0;i<list.size();i++)這種形式 System.out.println(str); } //第二種遍歷,把鏈表變為數組相關的內容進行遍歷 String[] strArray=new String[list.size()]; list.toArray(strArray); for(int i=0;i<strArray.length;i++) //這里也可以改寫為 foreach(String str:strArray)這種形式 { System.out.println(strArray[i]); } //第三種遍歷 使用迭代器進行相關遍歷 Iterator<String> ite=list.iterator(); while(ite.hasNext())//判斷下一個元素之后有值 { System.out.println(ite.next()); } } }
map遍歷
import java.util.*; public class Test{ public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("1", "value1"); map.put("2", "value2"); map.put("3", "value3"); //第一種:普遍使用,二次取值 System.out.println("通過Map.keySet遍歷key和value:"); for (String key : map.keySet()) { System.out.println("key= "+ key + " and value= " + map.get(key)); } //第二種 System.out.println("通過Map.entrySet使用iterator遍歷key和value:"); Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); } //第三種:推薦,尤其是容量大時 System.out.println("通過Map.entrySet遍歷key和value"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); } //第四種 System.out.println("通過Map.values()遍歷所有的value,但不能遍歷key"); for (String v : map.values()) { System.out.println("value= " + v); } } }
6、數組使用的幾個例子
數組和集合:
1.數組第一種定義方式
int[] counts = {1,2,3,4,5};
2.數組第二種定義方式(先初始化,后賦值)
int[] numbers = new int[3]; numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[0] = 1000;//在索引范圍以內可以更改
3.數組創建第三種方式
int[] nums = new int[] {1,2,3}; //修改 nums[0] = 1000;