天天看点

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;