集合:collection 在util包中
集合中存放的是對象。
Collection
List: ArrayList, LinkedList, Vector 元素有序不可重複
Set:HashSet, TreeSet 元素無序不能重複
1,List:特有的方法,凡是可以操作角標的方法多少它特有的方法。
add(index, element);
addAll(index, Collection);
remove(index);
set(index, element);
get(index);
subList(from, to);
listIterator();
indexOf(對象);
subList(start, end);
特有的迭代器ListIterator是Iterator的子接口。
List中對象的比較使用的是equals方法。
contains,remove底層調用的也是equals方法。
HashSet:底層數據結構是哈希表
HashSet保證元素唯一性的兩個方法:
如果元素HashCode相同,判斷equals是否爲true
如果元素hashCode值不同,則不會調用equals。
2,TreeSet,讀取元素時是排序的。
底層數據結構是二叉樹,保證元素唯一性的依據是compareTo的返回值。
方法一,元素需要實現Comparable接口,覆蓋compareTo方法。
class Student implements Comparable
{
public int compareTo(Object obj)
{
if (!(obj instanceof Student))
{
throw new RuntimeException("jllajl");
}
Student s = (Student)obj;
if (this.age > s.age)
{
return 1;
}
if (this.age == s.age)
{
return(this.name.compareTo(s.name));
}
return -1;
}
}
方法二,元素不具備比較性或不是所需的時。這時需要集合自身具有比較性。定義比較器。當兩種比較方式都存在時,比較器爲主。
class MyCompare implements Comparator
{
public int compare(Object o1, Object o2)
{
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int num = s1.getName().compareTo(s2.getName());
if(num==0)
return return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge());
return num;
}
}
TreeSet ts = new TreeSet(new MyCompare());//這裏就傳入了比較器。
泛型:JDK1.5以後出現。是一個安全機制。
<>內添加類型的限制。解決集合的不安全問題,因爲集合可以接受任何的類型。
什麼時候使用泛型呢?通常在集合中進行限定。
泛型可以定義在類上,這樣整個類內的功能都是用同一種類型。
泛型也可以定義在函數上,一個類內也就可以有多個泛型了。
如:public <T> void show(T t){}
如果靜態方法操作的應用數據類型不確定,可以將泛型定義在方法上。
還有一方法,限定泛型應用的類型範圍,這樣寫<>內。
public static void printColl(ArrayList<? extends Person> a1){}
<? super E>這樣限制下限,E及E的父類。
3,Map集合:
|--Hashtable 不可以存null 鍵值對,同步
|--HashMap 運行存null鍵值對,線程不同步
|--TreeMap二叉樹結構,線程不同步
<K, V> 鍵值對,保證key的唯一性。
clear();
containsValue(Object value);
containsKey(Object key);
get(Object key);
values();
put(k,value);
remove(Object key);
isEmpty();
size();
entrySet();
keySet();
Map集合的取出原理,用set集合存key,再取出對應的value。
4,Collections :它是一個集合類。
由在 collection 上進行操作或返回 collection 的靜態方法組成。它包含在 collection 上操作的多態算法,
sort();
max();
binarySearch();二分查找
fill();替換list中的元素
replaceAll();
reverseOrder()
swap();
shuffle();隨機方式排放元素。
Collections集合類提供了線程安全的方法,
synchronizedList();
Arrays 是操作數組的工具類。裏面很多靜態方法。
asList();將數組轉成list集合。不可以使用集合的增刪方法,因爲此時長度是固定的。
如果數組中的元素都是對象,那麼變成集合時,數組中的元素直接轉成集合中的元素。如果數組中的元素都是基本數據類型,那麼會將該數組作爲集合中的元素存在。這時可能就存數組名的地址。
增強for循環:只能獲取,不能對集合操作。
相對於傳統for循環,增強的for必須有被遍歷的目標。
HashMap<Integer, String> hm = new HashMap<Integer, String>();
…..
Set<Integer> keyset = hm.keySet();
for(Integer i : keyset)
{
System.out.println(hm.get(i));
}
------
for(Map.Entry<Integer, String> me : hm.entrySet())
{
System.out.println(me.getKey() + me.getValue());
}
5,可變參數:(T… a)
靜態導入: import static java.lang.System.*;那次後調用System成員方法時就不用加上System了。但有重名的方法時要指定是那個類的調用。