集合的由來:html
面嚮對象語言對事物都是以對象的形式來體現,爲了方便對多個對象的操做,就須要將對象進行存儲,集合就是存儲對象最經常使用的一種方式。java
集合特色:面試
1,用於存儲對象的容器。(容器自己就是一個對象,存在於堆內存中,裏面存的是對象的地址)
2,集合的長度是可變的。
3,集合中不能夠存儲基本數據類型值。 (只能存對象)api
小問題:想用集合存基本數據類型怎麼辦? 數組
裝箱、拆箱。 例:al.add(5); // 至關於al.add(new Integer(5));安全
集合和數組的區別:數據結構
數組雖然也能夠存儲對象,但長度是固定的,集合長度是可變的。app
數組中能夠存儲基本數據類型,集合只能存儲對象。框架
集合框架的構成及分類:(虛線爲接口)ide
下面分別整理集合框架中的幾個頂層接口。
Collection子接口以及經常使用實現類:
Collection接口
|--List接口:有序(存入和取出的順序一致),元素都有索引(角標),元素能夠重複。
|--Vector:內部是 數組 數據結構,是同步的。增刪,查詢都很慢!100%延長(幾乎不用了)
|--ArrayList:內部是 數組 數據結構,是不一樣步的。替代了Vector,查詢的速度快,增刪速度慢。50%延長。(查詢時是從容器的第一個元素日後找,因爲數組的內存空間是連續的,因此查詢快;增刪的話全部元素內存地址都要改變,因此增刪慢。)
|--LinkedList:內部是 鏈表 數據結構,是不一樣步的。增刪元素的速度很快。(同理,鏈表的內存空間是不連續的,因此查詢慢;增刪時只需改變單個指針的指向,因此快;)
|--Set接口:無序,元素不能重複。Set接口中的方法和Collection一致。
|--HashSet: 內部數據結構是哈希表 ,是不一樣步的。
|--LinkedHashSet:內部數據結構是哈希表和鏈表,是有順序的HashSet。
|--TreeSet:內部數據結構是有序的二叉樹,它的做用是提供有序的Set集合,是不一樣步的。
List接口:
有一個最大的共性特色就是均可以操做角標,因此LinkedList也是有索引的。list集合能夠完成對元素的增刪改查。
Set和List的區別:
1. Set 接口實例存儲的是無序的,不重複的數據。List 接口實例存儲的是有序的,能夠重複的元素 <最本質區別>。
2. Set檢索效率低下,刪除和插入效率高,插入和刪除不會引發元素位置改變 。
3. List和數組相似,能夠動態增加,根據實際存儲的數據的長度自動增加List的長度。查找元素效率高,插入刪除效率低,由於會引發其餘元素位置改變 。
ArryList和Vector可變長度數組的原理:
當默認長度的數組不夠存儲時,會創建一個新數組。將原來數組的內容拷貝到新的數組當中,並將新增長的元素追加到拷貝完的數組尾,若是仍然不夠重複上述動做。其中,ArryList的增長是以原來50%長度進行增長,而Vector是按照100%延長。
ArryList是線程不安全的,Vector是安全的:
因爲是否有鎖的判斷將影響效率,故Arrylist效率遠遠高於Vector。並且只要是經常使用的容器就不是同步的,由於同步效率比較低。
ArryList存取對象的一個小例子:
Person p1 = new Person("lisi1",21); ArrayList al = new ArrayList(); al.add(p1); al.add(new Person("lisi2",22)); al.add(new Person("lisi3",23)); al.add(new Person("lisi4",24)); Iterator it = al.iterator(); while(it.hasNext()){ // System.out.println(((Person) it.next()).getName()+"::"+((Person) it.next()).getAge()); //錯誤方式:不能這樣取,next()一次指針會移動一次,會輸出「lisi1::22 lisi3::24」 // 正確方式:拿到一個Person對象,而後取屬性。 Person p = (Person) it.next(); System.out.println(p.getName()+"--"+p.getAge()); }
如何保證HashSet的元素惟一性呢?
是經過對象的hashCode和equals方法來完成對象惟一性的:
->若是對象的hashCode值不一樣,那麼不用判斷equals方法,就直接存儲到哈希表中。
->若是對象的hashCode值相同,那麼要再次判斷對象的equals方法是否爲true:
若是爲true,視爲相同元素,不存;若是爲false,那麼視爲不一樣元素,就進行存儲。
記住:若是對象要存儲到HashSet集合中,該對象必須覆蓋hashCode方法和equals方法。
通常狀況下,若是定義的類會產生不少對象,好比人,學生,書,一般都須要覆蓋equals,hashCode方法,以創建對象判斷是否相同的依據。
例:往HashSet集合中存儲Person對象。若是姓名和年齡相同,視爲同一我的,視爲相同元素。
import java.util.HashSet; import java.util.Iterator; class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public int hashCode() { // System.out.println(this+".......hashCode"); return name.hashCode() + age * 27; // 乘以一個任意數,防止加了年齡之後HashCode仍相同 } @Override public boolean equals(Object obj) { // 健壯性判斷 if (this == obj) return true; if (!(obj instanceof Person)) throw new ClassCastException("類型錯誤"); // System.out.println(this+"....equals....."+obj); Person p = (Person) obj; return this.name.equals(p.name) && this.age == p.age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return name + ":" + age; } } public class HashSetTest { public static void main(String[] args) { HashSet hs = new HashSet(); /* * HashSet集合數據結構是哈希表,因此存儲元素的時候, * 使用的元素的hashCode方法來肯定位置,若是位置相同,在經過元素的equals來肯定是否相同。 * */ hs.add(new Person("lisi4", 24)); hs.add(new Person("lisi7", 27)); hs.add(new Person("lisi1", 21)); hs.add(new Person("lisi9", 29)); hs.add(new Person("lisi7", 27)); Iterator it = hs.iterator(); while (it.hasNext()) { Person p = (Person) it.next(); System.out.println(p); } } }
運行結果:
lisi1:21 lisi9:29 lisi4:24 lisi7:27
TreeSet默認判斷元素惟一性的方式:
根據Conpare接口的比較方法conpareTo的返回結果是不是0,是0,就是相同元素,不存。
下面,咱們給出兩種自定義判斷元素惟一性的方式:
方式一:
讓元素自身具有比較功能,即根據元素中的屬性來比較。採用這種方式須要元素實現Comparable接口,覆蓋compareTo方法。
例:往TreeSet集合中存儲Person對象。若是姓名和年齡相同,視爲同一我的,視爲相同元素。
import java.util.Iterator; import java.util.TreeSet; class Person implements Comparable { public String name; public int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String toString() { return name + ":" + age; } @Override public int compareTo(Object o) { Person p = (Person) o; /* 敲黑板劃重點,代碼簡潔方式 */ int temp = this.age - p.age; return temp == 0 ? this.name.compareTo(p.name) : temp; // 上面這兩句至關於底下這一段的簡潔形式 // if (this.age > p.age) // return 1; // if (this.age < p.age) // return -1; // else { // return this.name.compareTo(p.name); // } } public static void main(String[] args) { TreeSet<Person> ts = new TreeSet<Person>(); ts.add(new Person("zhangsan", 22)); ts.add(new Person("lisi", 27)); ts.add(new Person("wangermazi", 21)); ts.add(new Person("zhaosi", 25)); Iterator it = ts.iterator(); while (it.hasNext()) { Person person = (Person) it.next(); System.out.println(person.toString()); } } }
運行結果:
wangermazi:21 zhangsan:22 zhaosi:25 lisi:27
能夠看到,複寫compareTo方法後,元素根據age這個屬性進行了排序。
方式二:(開發用這個,掌握比較器的用法)
讓集合自身具有比較功能。本身寫一個比較器,先定義一個類實現Comparator接口,覆蓋compare方法。而後將該類對象做爲參數傳遞給TreeSet集合的構造函數。
再也不須要元素實現Conparable接口。
step1-新建比較器類ComparedByName.java,覆蓋compare方法:
import java.util.Comparator; public class ComparedByName implements Comparator { @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub Person p1 = (Person) o1; Person p2 = (Person) o2; int temp = p1.name.compareTo(p2.name); return temp == 0 ? p1.age - p2.age : temp; } }
step2-將比較器類類對象做爲參數傳遞給TreeSet集合的構造函數:
import java.util.Iterator; import java.util.TreeSet; class Person implements Comparable { public String name; public int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String toString() { return name + ":" + age; } @Override public int compareTo(Object o) { Person p = (Person) o; /* 敲黑板劃重點,代碼簡潔方式 */ int temp = this.age - p.age; return temp == 0 ? this.name.compareTo(p.name) : temp; // 上面這兩句至關於底下這一段的簡潔形式 // if (this.age > p.age) // return 1; // if (this.age < p.age) // return -1; // else { // return this.name.compareTo(p.name); // } } public static void main(String[] args) { TreeSet<Person> ts = new TreeSet<Person>(new ComparedByName()); ts.add(new Person("zhangsan", 22)); ts.add(new Person("lisi", 27)); ts.add(new Person("wangermazi", 21)); ts.add(new Person("zhaosi", 25)); Iterator it = ts.iterator(); while (it.hasNext()) { Person person = (Person) it.next(); System.out.println(person.toString()); } } }
運行結果:
lisi:27 wangermazi:21 zhangsan:22 zhaosi:25
此次咱們的比較器是根據元素屬性name進行排序的,複寫的compareTo方法是根據age進行排序的。
能夠看到,當兩種方法同時存在時,是按照比較器的方法來排序的。
思考:如何經過這種方式實現先進先出和先進後出?
讓比較器直接返回1或-1便可。
對 Collection 進行迭代的迭代器,即對全部的Collection容器進行元素取出的公共接口。
該迭代器對象依賴於具體容器,由於每個容器的數據結構都不一樣,因此該迭代器對象是在具體容器中進行內部實現的。(內部類,能夠看具體容器的源碼)
對於使用容器者而言,具體的實現方法不重要,只要經過具體容器獲取到該實現的迭代器的對象便可,也就是iterator()方法,而不用new。(Iterator<String> ite=list.iterator();)
小知識點:使用迭代器過程當中while和for的區別
1 第一種
2 Iterator<String> ite=list.iterator(); 3 while(ite.hasNext())//判斷下一個元素以後有值 4 { 5 System.out.println(ite.next()); 6 } 7 第二種 8 Iterator<String> ite=list.iterator(); 9 for(Iterator it = coll.iterator(); it.hasNext(); ){ 10 System.out.println(it.next()); 11 }
第一種方法while循環結束後迭代器對象還在內存中存在,還能繼續使用迭代器對象。
第二種方法for循環結束後迭代器對象就消失了,清理了內存,開發中第二種經常使用。
Iterator的一個子接口
|--ListIterator接口(列表迭代器)
應用場景:
顧名思義,只能用於List的迭代器。
在使用迭代器迭代的過程當中須要使用集合中的方法操做元素,出現ConcurrentModificationException異常時,具體看下面的例子。
出現異常狀況代碼:
Iterator it = list.iterator(); while(it.hasNext()){ Object obj = it.next();//java.util.ConcurrentModificationException //在使用迭代器的過程當中使用集合中的方法add()操做元素,出現異常。 //可使用Iterator接口的子接口ListIterator來完成在迭代中對元素進行更多的操做。 if(obj.equals("abc2")){ list.add("abc9"); } else System.out.println("next:"+obj); } System.out.println(list);
解決辦法代碼:
public static void main(String[] args) { List list = new ArrayList(); list.add("abc1"); list.add("abc2"); list.add("abc3"); System.out.println("list:"+list); ListIterator it = list.listIterator();//獲取列表迭代器對象 //它能夠實如今迭代過程當中完成對元素的增刪改查。 //注意:只有list集合具有該迭代功能. while(it.hasNext()){ Object obj = it.next(); if(obj.equals("abc2")){ it.add("abc9"); //ListIterator提供了add方法 } }
Map接口與Set相似,能夠對照着來學,好比比較器在TreeMap中也適用。
Map: 一次添加一對元素,Collection 一次添加一個元素。
Map也稱爲雙列集合,Collection集合也稱爲單列集合。
其實map集合中存儲的就是鍵值對,map集合中必須保證鍵的惟一性。
經常使用方法:
1,添加
value put(key,value):返回前一個和key關聯的值,若是沒有返回null.
2,刪除
void clear():清空map集合。
value remove(key):根據指定的key翻出這個鍵值對。
3,判斷
boolean containsKey(key):是否包含該key
boolean containsValue(value):是否包含該value
boolean isEmpty();是否爲空
4,獲取
value get(key):經過鍵獲取值,若是沒有該鍵返回null。固然,能夠經過是否返回null,來判斷是否包含指定鍵。
int size(): 獲取鍵值對的個數。
Map經常使用的子類:(*HashMap與Hashtable的區別,面試常問*,詳見這個博客。)
|--Hashtable :內部結構是哈希表,是同步的。不容許null做爲鍵,null做爲值。
|--Properties:用來存儲鍵值對型的配置文件的信息,能夠和IO技術相結合。
|--HashMap : 內部結構是哈希表,不是同步的。容許null做爲鍵,null做爲值。
|--TreeMap : 內部結構是二叉樹,不是同步的。能夠對Map集合中的鍵進行排序。
Map的迭代方法:
Map自己沒有迭代器。
方法一:利用Map接口的values()方法,返回此映射中包含的值的 Collection
(值不惟一),
而後經過Collecion的迭代器進行迭代。(只須要Value,不須要Key的時候)
public class MapDemo { public static void main(String[] args) { Map<Integer,String> map = new HashMap<Integer,String>(); method_2(map); } public static void method_2(Map<Integer,String> map){ map.put(8,"zhaoliu"); map.put(2,"zhaoliu"); map.put(7,"xiaoqiang"); map.put(6,"wangcai"); Collection<String> values = map.values(); Iterator<String> it2 = values.iterator(); while(it2.hasNext()){ System.out.println(it2.next()); } } }
方法二:經過keySet方法獲取map中全部的鍵所在的Set集合(Key和Set的都具備惟一性),
再經過Set的迭代器獲取到每個鍵,再對每個鍵經過Map集合的get方法獲取其對應的值便可。
Set<Integer> keySet = map.keySet(); Iterator<Integer> it = keySet.iterator(); while(it.hasNext()){ Integer key = it.next(); String value = map.get(key); System.out.println(key+":"+value); }
方法三:利用Map的內部接口Map.Entry<K,V>使用iterator。
經過Map的entrySet()方法,將鍵和值的映射關係做爲對象存儲到Set集合中。
這個映射關係的類型就是Map.Entry類型(結婚證)。
再經過Map.Entry對象的getKey和getValue獲取其中的鍵和值。
Set<Map.Entry<Integer, String>> entrySet = map.entrySet(); Iterator<Map.Entry<Integer, String>> it = entrySet.iterator(); while(it.hasNext()){ Map.Entry<Integer, String> me = it.next(); Integer key = me.getKey(); String value = me.getValue(); System.out.println(key+":"+value); }
方法四:經過Map.entrySet()方法遍歷key和value(推薦,尤爲是容量大時)
for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }
百度考到過HashMap中怎麼按value來排序。
和Set中比較器的用法相似,這裏咱們用內部類的形式來實現比較器。簡單的例子涵蓋了不少知識點。
1 public class HashMapTest { 2 // 將內部內修改成靜態,直接能夠在main函數中建立內部類實例 3 private static class ValueComparator implements Comparator<Map.Entry<Character, String>> { 4 @Override 5 public int compare(Map.Entry<Character, String> entryA, Map.Entry<Character, String> entryB) { 6 // 複寫的方法是compare,String類的方法是compareTo,不要記混。 7 return entryA.getValue().compareTo(entryB.getValue()); 8 } 9 } 10 11 public static void main(String[] args) { 12 Map<Character, String> map = new HashMap<>(); 13 map.put('c', "3"); 14 map.put('a', "5"); 15 map.put('b', "1"); 16 map.put('d', "2"); 17 System.out.println("Before Sort:"); 18 for (Map.Entry<Character, String> mapping : map.entrySet()) { 19 System.out.println(mapping.getKey() + ":" + mapping.getValue()); 20 } 21 22 List<Map.Entry<Character, String>> list = new ArrayList<>(map.entrySet()); 23 // 或者list.addAll(map.entrySet()); 24 ValueComparator vc = new ValueComparator(); 25 Collections.sort(list, vc); 26 27 System.out.println("After Sort:"); 28 for (Map.Entry<Character, String> mapping : list) { 29 System.out.println(mapping.getKey() + ":" + mapping.getValue()); 30 } 31 } 32 }
Collections是集合框架的工具類,裏面的方法都是靜態的。
例1:根據字符串長度的正序和倒序排序。
用到比較器的地方均可以用Collections.reverseOrder()。
static void |
reverse(List<?> list) 反轉指定列表中元素的順序。 |
|
static
|
reverseOrder() 返回一個比較器,它強行逆轉實現了 Comparable 接口的對象 collection 的天然順序。 |
|
static
|
reverseOrder(Comparator<T> cmp) 返回一個比較器,它強行逆轉指定比較器的順序。 |
比較器ComparatorByLength.java:
import java.util.Comparator; public class ComparatorByLength implements Comparator<String> { @Override public int compare(String o1, String o2) { int temp = o1.length() - o2.length(); return temp==0?o1.compareTo(o2): temp; } }
Demo:
public static void demo_3() { // reverse實現原理 /* * TreeSet<String> ts = new TreeSet<String>(new Comparator<String>() { @Override public int compare(String o1, String o2) { int temp = o2.compareTo(o1); return temp; } }); */ TreeSet<String> treeset = new TreeSet<String>(new ComparatorByLength()); treeset.add("abc"); treeset.add("hahaha"); treeset.add("zzz"); treeset.add("aa"); treeset.add("cba"); System.out.println(treeset); TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder(new ComparatorByLength()));//都是靜態方法,直接類名調用 ts.add("abc"); ts.add("hahaha"); ts.add("zzz"); ts.add("aa"); ts.add("cba"); System.out.println("after reverse:\t" + ts); } public static void main(String[] args) { demo_3(); }
[aa, abc, cba, zzz, hahaha]
after reverse: [hahaha, zzz, cba, abc, aa]
例2:用工具類Collections.sort()進行排序:
public static void demo_2() { List<String> list = new ArrayList<String>(); list.add("abcde"); list.add("cba"); list.add("aa"); list.add("zzz"); list.add("cba"); list.add("nbaa"); System.out.println(list); Collections.sort(list); System.out.println("after sort:\n" + list); Collections.sort(list, Collections.reverseOrder()); System.out.println("after reverse sort:\n" + list); int index = Collections.binarySearch(list, "cba"); System.out.println("index=" + index); // 獲取最大值。 String max = Collections.max(list, new ComparatorByLength()); System.out.println("maxLength=" + max); } public static void main(String[] args) { demo_2(); }
[abcde, cba, aa, zzz, cba, nbaa] after sort: [aa, abcde, cba, cba, nbaa, zzz] after reverse sort: [zzz, nbaa, cba, cba, abcde, aa] index=2 maxLength=abcde
例3:給非同步的集合加鎖,方法太多就不一一列舉了,本身查看API。(掌握,面試會問到)
static
|
synchronizedCollection(Collection<T> c) 返回指定 collection 支持的同步(線程安全的)collection。 |
|
static
|
synchronizedList(List<T> list) 返回指定列表支持的同步(線程安全的)列表。 |
|
static
|
synchronizedMap(Map<K,V> m) 返回由指定映射支持的同步(線程安全的)映射。 |
|
static
|
synchronizedSet(Set<T> s) 返回指定 set 支持的同步(線程安全的)set。 |
簡單說一下給集合加鎖的思想。
List list = new ArrayList();// 非同步的list。 list=MyCollections.synList(list);// 返回一個同步的list. class MyCollections{ /** * 返回一個加鎖的List * */ public static List synList(List list){ return new MyList(list); } // 內部類 private class MyList implements List{ private List list; private static final Object lock = new Object(); MyList(List list){ this.list = list; } public boolean add(Object obj){ synchronized(lock) { return list.add(obj); } } public boolean remove(Object obj){ synchronized(lock) { return list.remove(obj); } } } }
例4:將集合轉成數組,Arrays.asList()方法 (掌握)
應用場景:數組方法有限,須要使用集合中的方法操做數組元素時。
注意1:
數組的長度是固定的,因此對於集合的增刪方法(add()和remove())是不能使用的。
Demo:
public static void demo_1() { String[] arr = { "abc", "haha", "xixi" }; List<String> list = Arrays.asList(arr); boolean b1 = list.contains("xixi"); System.out.println("list contains:" + b1); // list.add("hiahia");//引起UnsupportedOperationException System.out.println(list); }
list contains:true [abc, haha, xixi]
注意2:
若是數組中的元素是對象(包裝器類型),那麼轉成集合時,直接將數組中的元素做爲集合中的元素進行集合存儲。(好比上面那個Demo)
若是數組中的元素是基本數據類型,那麼會將該*數組*做爲集合中的元素進行存儲。(好比下面這個Demo)
Demo:
public static void demo_2() { /* * 若是數組中的元素是對象,那麼轉成集合時,直接將數組中的元素做爲集合中的元素進行集合存儲。 * * 若是數組中的元素是基本類型數值,那麼會將該數組做爲集合中的元素進行存儲。 * */ int[] arr = { 31, 11, 51, 61 }; List<int[]> list = Arrays.asList(arr); System.out.println(list); System.out.println("數組的長度爲:" + list.size()); }
[[I@659e0bfd]
數組的長度爲:1
由結果能夠看出,當數組中的元素時int類型時,集合中存的元素是整個數組,集合的長度爲1而不是4。
例5:將數組轉成集合,List.toArray()方法
Object[] |
toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
|
<T> T[] |
toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
|
應用場景:對集合中的元素操做的方法進行限定,不容許對其進行增刪時。
注意:toArray方法須要傳入一個指定類型的數組,數組的長度如何定義呢?
若是定義的數組長度小於集合的size,那麼該方法會建立一個同類型並和集合相同size的數組。
若是定義的數組長度大於集合的size,那麼該方法就會使用指定的數組,存儲集合中的元素,其餘位置默認爲null。
因此,通常將數組的長度定義爲集合的size。
Demo:
public class ToArray { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("abc1"); list.add("abc2"); list.add("abc3"); String[] arr = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(arr)); } }
例6:foreach語句
應用場景:遍歷數組或Collection單列集合。
對數組的遍歷若是僅僅是獲取數組中的元素用foreach能夠簡化代碼,若是要對數組的角標進行操做建議使用傳統for循環。
格式:
for(類型 變量 :Collection集合|數組)
{}
Demo:
public class ForEachDemo { public static void main(String[] args) { // 遍歷數組 int[] arr = { 3, 1, 5, 7, 4 }; for (int i : arr) { System.out.println(i); } //遍歷List List<String> list = new ArrayList<String>(); list.add("abc1"); list.add("abc2"); list.add("abc3"); for (String s : list) { System.out.println(s); } // 遍歷map // 可使用高級for遍歷map集合嗎?不能直接用,可是將map轉成單列的set,就能夠用了。 Map<Integer, String> map = new HashMap<Integer, String>(); map.put(3, "zhagsan"); map.put(1, "wangyi"); map.put(7, "wagnwu"); map.put(4, "zhagsansan"); for (Integer key : map.keySet()) { String value = map.get(key); System.out.println(key + "::" + value); } for (Map.Entry<Integer, String> me : map.entrySet()) { Integer key = me.getKey(); String value = me.getValue(); System.out.println(key + ":" + value); } // 老式的迭代器寫法 Iterator<String> it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }