Java集合框架
<Java集合框架的四大接口>
Collection:存儲無序的、不唯一的數據;其下有List和Set兩大接口。
List:存儲有序的、不唯一的數據;
Set:存儲無序的、唯一的數據;
Map:以鍵值對的形式存儲數據,以鍵取值。鍵不能重復,但值可以重復。
接口的常用實現類:ArrayList、LinkedList、Vector、HashSet、LinkedHashSet、TreeSet、HashMap、LinkedHashMap、TreeMap、HashTable
一、List接口
是一個有序集合,繼承自Collection接口。現已知常用實現類有:ArrayList、LinkedList、Vector。
1. 常用方法:
add():在列表的最后添加元素;
add(index,obj):在列表的指定位置添加元素;
size():返回當前列表的元素個數
get(int index):返回下標為index的元素;
clear():清除列表中所有元素;
isEmpty():檢測列表是否為空;返回true/false;
contains():傳入一個對象,檢測列表中是否含有該對象;
indexOf():傳入一個對象,返回該對象在列表中首次出現的地址;
lastInsevOf():傳入一個對象,返回該對象在列表中最后一次出現的地址;
remove():傳入一個下標,或者一個對象,刪除指定元素;如果刪除指定對象,需要重寫equals()方法,比對傳入的對象是不是屬於原列表,如果屬於,結果返回true;
set(index,obj):用新傳入的對象,將指定位置的元素替換掉,返回被替換前的元素對象;
subList():截取一個子列表返回List類型;
toArray():將列表轉為數組,返回一個Object[]類型;
iterator():使用迭代器遍歷。
2. 如何輸出List列表?
a. for循環;
b. foreach遍歷(比較常用);
c. 使用迭代器遍歷列表;
3. List接口的常用實現類:
ArrayList和LinkedList實現類是繼承自List接口的,所以List的常用方法它們也是適用的。
a. ArrayList
ArrayList實現了一個長度可變的數組,在內存空間中開辟一串連續的空間。
b. LinkedList
LinkedList使用鏈表結構存儲數據,在插入和刪除元素是速度非常快。
1 //ArrayList實現類 2 ArrayList<String> list1=new ArrayList<String>(); 3 list1.add("第一條數據"); 4 list1.add("第二條數據"); 5 list1.add("第三條數據"); 6 list1.add("第四條數據"); 7 list1.add("第五條數據"); 8 list1.add("第三條數據"); 9 list1.add(2,"第六條數據"); //在第三條數據后添加“第六條數據” 10 11 System.out.println(list1.size()); //返回列表長度 12 System.out.println(list1.get(2)); //返回“第六條數據” 13 //list1.clear(); //清除所有數據 14 System.out.println(list1.isEmpty()); //返回false 15 System.out.println(list1.contains("第一條數據")); //返回true 16 System.out.println(list1.indexOf("第三條數據")); //返回3 17 System.out.println(list1.lastIndexOf("第三條數據")); //返回6 18 System.out.println(list1.remove(1)); //刪除“第二條數據” 19 System.out.println(list1.set(0, "替換第一條數據")); //替換第一條數據 20 List list=list1.subList(2, 5); //截取第三到第五條數據,返回List 21 System.out.println(list1.toString()); //轉成數組 22 23 //LinkedList實現類 24 LinkedList<News> list2=new LinkedList<News>(); 25 list2.add(new News(1,"xxxxxxx","趙")); 26 list2.add(new News(2,"sssssss","錢")); 27 list2.add(new News(3,"yyyyyyy","孫")); 28 list2.add(new News(4,"nnnnnnn","李")); 29 list2.add(new News(5,"rrrrrrr","周")); 30 System.out.println(list2.contains(new News(3,"yyyyyyy","孫"))); //返回為true;重寫equals()方法;如果不重寫equals()方法,返回為false; 31 System.out.println(list2.remove(new News(1,"xxxxxxx","趙"))); //返回為true 32 33 /* 34 * 使用for循環遍歷 35 */ 36 for (int i = 0; i < list1.size(); i++) { 37 if(list1.get(i) instanceof String){ //判斷傳入的數據屬不屬於String類型 38 String str=list1.get(i); 39 System.out.println(str); 40 } 41 } 42 /* 43 * foreach遍歷 44 */ 45 for (News news : list2) { 46 System.out.println(news.getId()+" "+news.getTitle()+"\t"+news.getAuthor()); 47 } 48 /* 49 * 迭代器遍歷 50 */ 51 Iterator<String> iter=list.iterator(); 52 while(iter.hasNext()){ //判斷list有沒有下一條 53 String s=iter.next(); //字符串取到下一條 54 System.out.println(s); 55 } 56
1 /** 2 *News類 3 */ 4 class News{ 5 private int id; 6 private String title; 7 private String author; 8 9 @Override 10 public boolean equals(Object obj) { 11 if (this == obj) 12 return true; 13 if (obj == null) 14 return false; 15 if (getClass() != obj.getClass()) 16 return false; 17 News other = (News) obj; 18 if (author == null) { 19 if (other.author != null) 20 return false; 21 } else if (!author.equals(other.author)) 22 return false; 23 if (id != other.id) 24 return false; 25 if (title == null) { 26 if (other.title != null) 27 return false; 28 } else if (!title.equals(other.title)) 29 return false; 30 return true; 31 } 32 public News() { 33 super(); 34 } 35 public News(int id, String title, String author) { 36 super(); 37 this.id = id; 38 this.title = title; 39 this.author = author; 40 } 41 public int getId() { 42 return id; 43 } 44 public void setId(int id) { 45 this.id = id; 46 } 47 public String getTitle() { 48 return title; 49 } 50 public void setTitle(String title) { 51 this.title = title; 52 } 53 public String getAuthor() { 54 return author; 55 } 56 public void setAuthor(String author) { 57 this.author = author; 58 } 59 60 61 }
二、Set接口
1. 常用方法:
與List接口基本相同。但是Set接口中的元素是無序的,因此沒有與下標有關的方法。例如:get(index)、remove(index)、add(index,obj)
2. Set接口的現已知常用實現類有:
HashSet、LinkedHashSet、TreeSet
3. HashSet
底層是HashMap的相關方法,傳入數據后,根據數據的hashCode進行散列運算,得到一個散列值后再進行運算,確定元素在序列中存儲的位置。
所以,使用HashSet存數據必須在實體類中重寫hashCode和equals方法!!
1 //HashSet無序的 2 Set<String> set1=new HashSet<String>(); 3 set1.add("set1"); 4 set1.add("set2"); 5 set1.add("set3"); 6 set1.add("set4"); 7 set1.add("set5"); 8 9 //foreach遍歷 10 for (String set : set1) { 11 System.out.println(set); 12 } 13
4. LinkedHashSet
在HashSet的基礎上,新增了一個鏈表。用鏈表來記錄HashSet種元素放入的順序;HashSet依然是無序的,但鏈表會按照存入的順序存儲。
1 //LinkedHashSet按照放入的順序輸出 2 Set<Person> set2=new LinkedHashSet<Person>(); 3 // set2.addAll(set1); //追加set1的所有數據 4 set2.add(new Person(1,"紅")); 5 set2.add(new Person(2,"黃")); 6 set2.add(new Person(3,"藍")); 7 set2.add(new Person(4,"綠")); 8 set2.add(new Person(4,"綠")); 9 10 //迭代器遍歷 11 Iterator<Person> iter=set2.iterator(); 12 while(iter.hasNext()){ 13 Person p=iter.next(); 14 System.out.println(p.getId()+"\t"+p.getName()); 15 } 16 17 class Person{ 18 private int id; 19 private String name; 20 21 /* 22 * 如果不重寫hashCode和equals方法,存入相同數據時將無法比對 23 * 24 */ 25 @Override 26 public int hashCode() { 27 final int prime = 31; 28 int result = 1; 29 result = prime * result + id; 30 result = prime * result + ((name == null) ? 0 : name.hashCode()); 31 return result; 32 } 33 @Override 34 public boolean equals(Object obj) { 35 if (this == obj) 36 return true; 37 if (obj == null) 38 return false; 39 if (getClass() != obj.getClass()) 40 return false; 41 Person other = (Person) obj; 42 if (id != other.id) 43 return false; 44 if (name == null) { 45 if (other.name != null) 46 return false; 47 } else if (!name.equals(other.name)) 48 return false; 49 return true; 50 } 51 public Person() { 52 super(); 53 } 54 public Person(int id, String name) { 55 super(); 56 this.id = id; 57 this.name = name; 58 } 59 public int getId() { 60 return id; 61 } 62 public void setId(int id) { 63 this.id = id; 64 } 65 public String getName() { 66 return name; 67 } 68 public void setName(String name) { 69 this.name = name; 70 } 71 72 }
5. TreeSet
將存入的數據,進行排序,然后輸出。
如果傳入的是一個實體對象,那么需要傳入比較器:實體類實現Comparable接口,並重寫CompareTo方法;
1 //TreeSet從小到大輸出。存入元素,默認升序排序;存入實體對象,需要傳入比較器 2 Set<Person> set3=new TreeSet<Person>(); 3 set3.add(new Person(11,"a")); 4 set3.add(new Person(22,"b")); 5 set3.add(new Person(33,"c")); 6 set3.add(new Person(44,"d")); 7 8 //迭代器遍歷 9 Iterator<Person> iter=set3.iterator(); 10 while(iter.hasNext()){ 11 Person p=iter.next(); 12 System.out.println(p.getId()+"\t"+p.getName()); 13 } 14 15 class Person implements Comparable{ //實現 16 private int id; 17 private String name; 18 19 //compareTo方法判斷傳入的對象和已有對象 20 @Override 21 public int compareTo(Object o) { 22 Person p=null; 23 if(o instanceof Person){ 24 p=(Person)o; 25 }else{ 26 return 0; 27 } 28 return this.id -p.getId(); //為正數,升序;為負數,降序;等於0,位置不變 29 } 30 31 public Person() { 32 super(); 33 } 34 public Person(int id, String name) { 35 super(); 36 this.id = id; 37 this.name = name; 38 } 39 public int getId() { 40 return id; 41 } 42 public void setId(int id) { 43 this.id = id; 44 } 45 public String getName() { 46 return name; 47 } 48 public void setName(String name) { 49 this.name = name; 50 } 51 52 53 }
三、Map接口
1. Map接口的特點:
以鍵值對的形式存儲數據,以鍵取值。鍵不能重復,值可以重復。
2. Map接口的現已知常用實現類有:
HashMap、HashTable、LinkedHashMap、TreeMap
3. 常用方法:
put(key,value):向Map的最后追加一個鍵值對;
get(key):通過鍵,取到一個值;
clear():清除Map中的所有數據;
containsKey(key):檢測是否包含指定的鍵;
containsValue(obj):檢測是否包含指定的值;
replace():替換指定鍵的值;
4. 遍歷Map
a. keySet():返回Set,先取鍵,再取值;
b. values():返回Collection,直接取值;
c. 取代一個entry鍵值對,返回Set<Entry<>>;
1 Map<String, String> map1=new HashMap<String, String>(); 2 map1.put("01", "aaaaaa"); 3 map1.put("02", "bbbbbb"); 4 map1.put("03", "cccccc"); 5 map1.put("04", "dddddd"); 6 // map1.clear(); //清除所有數據 7 System.out.println(map1.containsKey("01")); //返回true 8 System.out.println(map1.containsValue("aaaa")); //返回false 9 System.out.println(map1.replace("03", "dddddd")); //將cccccc替換為dddddd 10 System.out.println(map1.get("02")); //返回bbbbbb 11 12 /** 13 * 遍歷Map的方式一,先取鍵,再取值 14 */ 15 Set<String> keys=map1.keySet(); //取到所有鍵 16 Iterator<String> iter=keys.iterator(); 17 while(iter.hasNext()){ //迭代器遍歷取到每一個鍵 18 String key=iter.next(); 19 System.out.println(key+" "+map1.get(key)); //key:取到鍵 map1.get(key):取到每個鍵對應的值 20 } 21 22 /** 23 * 遍歷Map的方式二,直接取值;只能取到值 24 */ 25 Collection<String> values = map1.values(); 26 Iterator<String> iter1= values.iterator(); 27 while(iter1.hasNext()){ 28 System.out.println(iter1.next()); 29 } 30 31 /** 32 * 遍歷Map的方式三,取到一個entry鍵值對 33 */ 34 Set<Entry<String,String>> set= map1.entrySet(); 35 Iterator<Entry<String,String>> iter2=set.iterator(); 36 while(iter2.hasNext()){ 37 Entry<String,String> entry=iter2.next(); 38 System.out.println(entry.getKey()+" "+entry.getValue()); 39 } 40
5. LinkedHashMap
可以使用列表,記錄數據放入的次序,輸出的順序與放入的順序一致。與LinkEDHashSet一樣。
6. TreeMap
根據鍵的順序,進行排序后輸出。與TreeSet。
如果傳入的是實體對象,必須重寫比較函數。
7. HashMap和HashTable的區別?
a. HashTable是線程安全的,HashMap是線程不安全的;
b. HashTable的鍵不能為null,HashMap的鍵可以為null;
c. HashTable繼承自Dirctionary字典類,HashMap繼承自abstract類;
d. 擴容大小:HashTable兩倍,HashMap兩倍加一;
e. 初始容量:HashTable為11,HashMap為16;兩者的填充因子默認都是0.75;