集合的做用:
1,在類的內部,對數據進行組織
2,簡單而快速的搜索大數量的條目
3,有的集合接口,提供了一系列排列有序的元素,而且能夠在序列中間快速的插入或者刪除有關元素
4,有的集合接口提供了映射的關係,能夠經過關鍵字(key)去快速查找到對應的惟一對象,而這個關鍵字能夠是任意的類型java
爲什麼選擇集合而不是數組
數組長度固定,集合長度可變
數組只能經過下標訪問,類型固定,而集合能夠經過任意類型查找所映射的具體對象數組
collection map 是接口
Collection 接口,子接口以及實現類
Collection接口
1,是list set和queue接口的父接口
2,定義了可用於操做list set和queue的方法-增刪改查框架
List接口以及實現類-ArrayList
1,List是元素有序而且能夠重複的集合,被稱爲序列
2,list能夠精確的控制每個元素的插入位置,或刪除某一個元素
3,ArrayList-數組序列,是list的一個重要實現類。
4,ArrayList底層是由數組實現的。eclipse
如何經過迭代器來遍歷List
Iterator it =this
selectedCourses.iterator(); while(it.hasNext()){ course cr = (course) it.next(); System.out.println(cr.id+","+cr.name); }
更改集合內容
selectedCourses.set(0, new course("5","michael"));spa
泛型中的元素,能夠是任意類型的對象,(對象的引用)
若是把某個對象放入集合,則會忽略它的類型,把它看成object類處理
泛型規定某個集合只能夠存放特定類型的對象,會在編譯期間對其進行檢查code
set是元素無序而且不可重複的集合,被稱爲集
HashSet 是set的一個重要的實現類,哈希集 (無序而且不可重複)對象
由於set是無序的,因此不能用 List的get方法遍歷取值,每一次遍歷拿出來的都是不同的值接口
在map中key值是不能夠重複的,可是value值是能夠重複的
每個鍵key最多隻能映射到一個值value
Map接口提供了分別返回key值集合,value值集合以及entry 鍵值對集合的方法
Map支持泛型,形如 Map<K,V>圖片
keyset集合;
Set<String> keyset = student.keySet();
entry鍵值對
Set<Entry<String,Student>> entry = student.entrySet();
for(Entry<String,Student> ent:entry){ System.out.println(ent.getKey()); System.out.println(ent.getValue()); }
Map 也能夠修改 put方法 Map
Student st = new Student("1","nmae");
student.put("3", st);
重寫HashCode方法判斷是否相等
Object定義了HashCode方法,返回對象的hash碼的值
當咱們調用hashset的contains方法的時候,是先調用每個元素的hashcode值返回hash碼,在
每個hash碼相對的前提下調用equals方法去判斷是否相等,只用在這兩個都相等的前提下才能判斷HashSet包含某個元素
eclipse能夠自動生成hashcode和equals方法
comparable 接口
comparator 接口
java結合框架
Student類實現了comparable接口 public int compareTo(Student o) { // TODO Auto-generated method stub return this.id.compareTo(o.id);//利用id進行比較 } public void testSortt(){ List<Student> studentList = new ArrayList<Student>(); Student s1 = new Student("1","s1"); Student s2 = new Student("2","s2"); Student s3 = new Student("3","s3"); Student s4 = new Student("4","s4"); Student s5 = new Student("5","s5"); studentList.add(s1); studentList.add(s2); studentList.add(s3); studentList.add(s4); studentList.add(s5); Collections.sort(studentList);//student 類必須實現comparable接口 for(Student s:studentList){ System.out.println(s.id+","+s.name); } }
public class StudentComparator implements Comparator<Student> { public int compare(Student o1, Student o2) { //comparator定義臨時的規則 //若是是 0,兩個對象相等 //正數 o1>o2 //負數 o1<o2 return o1.name.compareTo(o2.name); } } Collections.sort(studentList,new StudentComparator()); for(Student s:studentList){ System.out.println(s.id+","+s.name); }