集合类
集合类用于存储一组对象,其中的每个对象称之为元素,经常会用以的有Vector,Enumeration,ArrayList,Collection,Iterator,Set,List等集合和接口
-------------------------------------------------------------------
***Vector类与Enumeration接口****
例:将键盘上输入的一个数字序列中的每位数字存储在Vector对象中,然后在屏幕上打印出每位数字相加的结果,例如,输入32,打印出5;输入1234打印出10
import java.util.*;
public class TestVector {
public static void main(String[] args) {
int b=0;
Vector v=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
{ int num=b-'0';
v.addElement(new Integer(num));
}
}
int sum=0;
Enumeration e=v.elements();
while(e.hasMoreElements())
{ Integer intobj = (Integer)e.nextElement();
sum+=intobj.intValue();
}
System.out.println(sum);
}
}
-----------------------------------------------------------
***Collection接口与Iterator接口***
不能直接用Collection接口类创建对象,ArrayList类就是一个实现Collection接口的类。
*例: 用ArrayList和Iterator改写上面的例子程序
import java.util.*;
public class TestCollection {
public static void main(String[] args) {
int b=0;
ArrayList v=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
{ int num=b-'0';
v.add(new Integer(num));
}
}
int sum=0;
Iterator e=v.iterator();
while(e.hasNext())
{ Integer intobj = (Integer)e.next();
sum+=intobj.intValue();
}
System.out.println(sum);
}
}
-------------------------------------------------------
***什么时候用Vector,什么时候用ArrayList呢***
1. Vector类中的所有方法都是线程同步的,两个线程并发访问Vector对象将是安全的,但只有一个线程访问Vector对象时,因为源程序仍调用了同步方法,需要额外的临视器检查,运行效率要低些。
2. ArrayList类中的所有方法是非同步的,所以在没有多线程安全问题时,最好用ArrayList,程序的效率会高些。在有线程安全问题,且我们的程序又没有自己处理时(自己处理是指对调用ArrayList的代码或方法加上同步代码同步处理),只能用Vector.
------------------------------------------------------------
***Collection,set,List的区别***
Collection是Set和List接口的父类
-Collection 各元素对象之间没有指定的顺序,允许有重复元素和多个null元素对象。
-Set各元素对象之间没有指定的顺序,不允许有重复元素,最多允许有一个null元素对象。
-List各元素对象之间有指定的顺序,允许有重复元素和多个null元素对象。
ArrayList是List接口的子类
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); //用Collections类的sort静态方法对其进行排序
System.out.println(al.toString());
}
}
Collections中的所有方法都是静态的,它是用于操纵集合对象,它本身不是集合类对象