數組
數組在內存中開闢一段連續的空間。數組必須指定大小,下標從0開始,不能越界。
數組定義
int[] intArray=new int[3];
intArray[0]=100;
intArray[1]=100;
intArray[2]=100;
intArray[1]=null;//刪除數組元素只能置空
數組循環
for(int i=0;i<intArray.length;i++){
System.out.println(intArray[i]);
}
集合Collection
Collection分爲List、Map和Set。
List分爲ArrayList和LinkedList(均實現了List接口),ArrayList在內存中開闢一段連續的空間,LinkedList空間可以不連續,通過指針指向。ArrayList訪問元素快,LinkedList添加刪除元素快。List無需指定大小,下標從0開始,不能越界。
Map分爲HashMap和TreeMap。TreeMap是按Key值進行排序。LinkedHashMap繼承HashMap,HashMap不保證順序,LinkedHashMap保證順序,LinkedHashMap繼承自HashMap。
Set分爲HashSet和TreeSet。
集合定義
List與Set的區別是:Set去重。
//List
List<String> list = new ArrayList<String>();
System.out.println(list);
System.out.println(list.get(2));
System.out.println(list.size());
//Set
Set<Object> set=new HashSet<Object>();
set.add("1");
System.out.println(set.size());
//Map
Map<String,Object> map=new HashMap<String, Object>();
map.put("name","zhangsan");
map.get("name");
System.out.println(map);
集合循環
//增強類型
for(String string:list){
System.out.println(string);
list.remove(string);
list.add(string);
}
//迭代寫法一
for(Iterator iterator=list.iterator();iterator.hasNext;){
String string=(String) iterator.next();
iterator.remove();
}
//迭代寫法二
Iterator iterator=list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}