*集合类用于存储一组对象,其中的每个对象称之为元素。经常会用的到的有:Vector类、Enumeration、ArrayList、Collection、Iterator、Set、List等集合类和接口。
编程例子:
将键盘中输入的数字序列中的每位数字存储在Vector对象中,然后再屏幕上打印每位数字相加的结果。例如,输入123,打印出9,输入1234,打印出10.
import java.util.*; class TestVector{ public static void main(String[] args){ int b = 0; Vector vt = new Vector(); System.out.println("please enter number:"); while(true){ try{ b = System.in.read(); }catch(Exception e){ e.printStackTrace(); } if(b=='/r' || b=='/n'){ //如果输入的是回车或换行,表示读入完毕。 break; }else{ Integer intObj = new Integer(b-'0'); vt.addElement(intObj); //将读入的对象存储到Vector对象中 } } int sum = 0; Enumeration e = vt.elements(); while(e.hasMoreElements()){ //hasMoreElements()返回一个boolean值,用于判定下一个对象是否为空 Integer intObj = (Integer)e.nextElement(); //nextElement()返回的是一个Object的对象,此处对它进行类型转换 sum += intObj.intValue(); } System.out.println(sum); } }
用collection,Iterator,ArrayList代替enumeration和Vector完成上面的例子。
import java.util.*; class TestIterator{ public static void main(String[] args){ int b = 0; ArrayList vt = new ArrayList(); System.out.println("please enter number:"); while(true){ try{ b = System.in.read(); }catch(Exception e){ e.printStackTrace(); } if(b=='/r' || b=='/n'){ //如果输入的是回车或换行,表示读入完毕。 break; }else{ Integer intObj = new Integer(b-'0'); vt.add(intObj); //将读入的对象存储到ArrayList对象中 } } int sum = 0; Iterator e = vt.iterator(); while(e.hasNext()){ //用hasnext()代替hasMoreElements()返回一个boolean值,用于判定下一个对象是否为空 Integer intObj = (Integer)e.next(); //用next()代替nextElement()返回的是一个Object的对象,此处对它进行类型转换 sum += intObj.intValue(); } System.out.println(sum); } }
使用Vector类和ArrayList类的区别:
Vector类的所有方法都是同步的,即使只有一个线程在访问,也会启用监视器,使用时会造成效率较低。
Iterator类 的方法没有同步,需要开发人员自己保证线程的安全,但运行效率较高。
Collection、Set、List的区别如下:*Collections对象元素之间没有固定顺序,允许有重复元素和多个null对象。*Set对象 元素之间没有指定顺序,不允许重复元素,只允许有一个null对象。*List对象元素间可以指定顺序,允许有重复元素和多个null对象。(ArrayList就是实现了List接口的类)
以下例子尝试对ArrayList排序输出。
import java.util.*; public class TestSort{ public static void main(String[] args){ ArrayList al = new ArrayList(); al.add(new Integer(1)); al.add(new Integer(3)); al.add(new Integer(2)); System.out.println(al.toString()); Collections.sort(al); System.out.println(al.toString()); } }