標籤:迭代 set system 工具 color pre 注意 移除 link
1.集合架構
a.架構:為了實現某一目的或功能,而預先提供的一系列封裝好的、具有繼承或實現關係的類與集合
b.集合:①定義:Java中對一些資料結構和演算法進行封裝,即封裝(集合也是一種對象)
②特點:元素類型可以不同,集合長度可變,空間不固定
c.集合架構:提供了管理集合的介面和類
2.Collection 與 Collections
a.Collection:是一個介面,裝東西的集合介面 (核心介面)
b.Collections:是一個演算法類,操作即可的演算法類
3.Collection
Collection(核心介面):a.List(列表):①ArrayList
②LinkedList
b.Set(集):HashSet
c.Map(映射):①HashMap
②Properties
4.List——列表
a.特點:①線性(有序,元素的放入順序和元素的儲存順序保持一致)
②表現上,List最大的特點就是有下標
b. ArrayList:就是作為一個數組的封裝出現的,底層就是數組
c. LinkedList:底層封裝的是一個雙向鏈表
d.應用:①當需要做大量的查詢動作的時候,使用ArrayList
②當需要做大量的增加刪除動作(特別是往中間增刪),使用LinkedList
e.方法:①聲明:
LinkedList<StudentBean> lst = new LinkedList<StudentBean>();
註:泛型:用來控制集合只能操作某一種資料類型<>
②增添:
lst.add(" ");lst.add(new Date());lst.add(new StudentBean("zhao4",32,76));lst.add(100);
③長度:
int size = lst.size();
④修改:
lst.set(0, new StudentBean("zhang3feng",102,45));
⑤刪除:
lst.remove(0);
⑥擷取某個元素:
StudentBean stu = (StudentBean)lst.get(1);StudentBean stu = lst.get(1); //加上泛型不需強轉
⑦遍曆:
方法一:使用普通for迴圈
方法二:使用迭代器---Iterator完成遍曆----是集合架構類Collection直接分支專用(特點:沒有下標,從頭到尾走一遍)
Iterator<StudentBean> it = lst.iterator();while(it.hasNext()){ StudentBean tmpStu = it.next(); System.out.println(tmpStu.getName());}
方法三:for-each迴圈:底層封裝的就是迭代器,但文法更簡單,還可以運算元組
for(StudentBean tmpStu : lst){ System.out.println(tmpStu.getName());}
5.Set——集
a.特點:①不能放置重複元素、無序
②表象上,Set沒有下標
b.HashSet 的不重複性判斷:
①調用equals方法得到兩個對象比較為true
②兩個元素的hashcode值保持一致
c.方法:
①增添:
set.add("hello");set.add(new Date());set.add(new StudentBean("zhang3",18,80));set.add(200);
②長度:
int size = set.size();
③刪除:只能根據對象進行刪除,還是用的equals和hashCode來判斷到底刪除哪個對象
set.remove(new StudentBean("zhang3",18,80));
④修改(沒有修改方法)
⑤遍曆:
1.不支援普通for迴圈
2.支援迭代器
3.支援for-each
6.Map——映射
a.特點:①索引值對。鍵要求唯一,值可以重複
②放入元素的順序和儲存順序無關
b.常用子類:HashMap(主要用於集合操作)、Properteis(專用於操作屬性檔案)
c.方法:
①聲明:
HashMap<String, StudentBean> map = new HashMap<String, StudentBean>();
②增添:
map.put("j34001", new StudentBean("zhang3",18,80));
③長度:
int size = set.size();
④修改:
map.put("j34001", new StudentBean("zhao6",24,75));
⑤刪除:
map.remove("j34003"); //通過鍵去移除元素
⑥擷取指定元素對象:
StudentBean stu = map.get("j34003");
⑦遍曆:不能同時遍曆鍵和值,只能分開遍曆
遍曆鍵:
Set<String> keySet = map.keySet(); //得到所有的鍵,裝入一個Set集合中,返回給調用者for(String key : keySet){ System.out.println(key);}
遍曆值:
Collection<StudentBean> allStus = map.values(); //得到所有的值,裝入一個Collection集合中,返回給調用者for(StudentBean tmpStu : allStus){ System.out.println(tmpStu.getName());}
7.Collections工具類
a.Collections 與 Arrays:
①Collections:操作集合
②Arrays:運算元組
b.方法:
System.out.println(Collections.max(lst)); //求最大System.out.println(Collections.min(lst)); //求最小Collections.sort(lst); //排序(只能傳List)內建內部比較子Collections.sort(lst,new StudentComparator()); //排序 提供外部比較子Collections.reverse(lst); //反轉Collections.shuffle(lst); //混排--隨機打亂排序
8.比較子:
a.Comparable:內部比較子
b.Comparator:外部比較子
c.注意:Comparable 中的 ComparaTo()方法中,返回的正數、負數,依賴於根據比較規則兩個元素的位置之差
Java 之 集合架構(JCF)