天天看點

java之路,集合類

集合架構:

所謂架構就是一個類庫的集合。集合架構就是一個用來表示和操作集合的統一的架構,包含了實作集合的接口與類。

Collection:集合層次中的根接口,JDK沒有提供這個接口直接的實作類。集合就是對象,它表示了一組對象。

Set:不能包含重複的元素。SortedSet是一個按照升序排列元素的Set。

List:是一個有序的集合,可以包含重複的元素。提供了按索引通路的方式。所謂有序是指List中元素按照一定的次序擺放

Map:包含了key-value對。Map不能包含重複的key。SortedMap是一個按照升序排列key的Map。

ArrayList:我們可以将其看作是能夠自動增長容量的數組。

利用ArrayList的toArray()傳回一個數組。

Arrays.asList()傳回一個清單。

疊代器(Iterator) 給我們提供了一種通用的方式來通路集合中的元素

import java.util.*

class ArrayListTest

{

 public static void printElements(Collection c)   //列印元素

 {

  Iterator it = c.itorater();

  while(it.hasNext())

  {

   System.out.println(it.next); 

  }

 }

 public static void main(String[] args)

  ArrayList a1 = new ArrayList();

  a1.add("zs");

  a1.add("ls");

  a1.add("ww");

  printElement(a1);

  a1.add(new Point(0,0));

  a1.add(new Point(1,1));

  a1.add(new Point(2,2));

  for(int i=0; i

   System.out.println(a1.get(i));  //get方法擷取元素

  System.out.println(a1);         //調用toString方法

  Object[] obj = a1.toArray();     //傳回一個包含元素的對象數組,Object類型

   System.out.println(obj[i]);

  List l = array.asList(obj);    //從數組傳回一個固定長度的連結清單

  System.out.println(l);

  l.add("wj");                   //錯誤,l的長度固定了

  Iterator it = a1.iterator();    //疊代器友善操作數組

  while(it.haaNext())             //hasNext判斷有沒有下一個元素

   System.out.println(it.next());  //next傳回下一個元素

  Student st1 = new Student(0, "zs");

  Student st2 = new Student(1, "ls");

  Student st3 = new Student(2, "ww");

  a1.add(st1);

  a1.add(st2);

  a1.add(st3);

  Collections.sort(a1);  //自然排序

  Collections.sort(a1,new Student.StudentComparator());

  Collections.sort(a1,Collections.reverseOrder());  //反向排序

  printElements(a1);

}

class Point

 int i,j;

 Point(int x, int y)

  this.x = x;

  this.y = y;

 public String toString()

  return "x=:" + x + ";" + "y=:" + y;

Collections類

排序:Collections.sort()   //對連結清單進行排序

(1)自然排尋(natural ordering );  //自然排序:2在3的前面,字母a在字母b的前面

(2)實作比較器(Comparator)接口。

取最大和最小的元素:Collections.max()、Collections.min()。

在已排序的List中搜尋指定的元素:Collectons.binarySearch()

class Student impelments Comparable  //實作Comparable接口

 int num;

 String name;

 Student(int num, String name)

  this.num = num;

  this.name = name;

 static class StudentComparator imlements Comparator

  public int compare(Object o1, Object o2)

   Student s1 = (Student)o1;

   Student s2 = (Student)o2;

   int result = s1.num > s2.num ? 1 : (s1.num == s2.num ? 0 : -1);

   if(result == 0)

   {

    result = s1.name.compareTo(s2.name)   //學号相同,比較名字

   }

   return result;

 public int compareTo(Object o)    //覆寫compareTo方法

  Student s = (Student)o;

  return num > s.num ? 1:(num == s.num ? 0: -1);

 public String toString(Student s)

  return "num =:" + num + "name=:" + name;