搜尋此網誌

2012年3月26日 星期一

Java ArrayList


public class ArrayListDemo {

public static void main(String[] args) {
/**
* Following example will cause a run time exception:
* java.lang.ClassCastException, although no compilation error happened.
*/

/*
* int sum = 0;
* ArrayList al = new ArrayList();
* al.add("1");
* al.add(new Integer(2));
* for (int i = 0; i < al.size(); i++) {
* sum+= (Integer)al.get(i);
* }
* System.out.println(sum);
*/

/**
* Following example will fix above problem.
*/
int sum = 0;
ArrayList al = new ArrayList();
// al.add("1"); this line has a compilation error.
al.add(new Integer(1));
al.add(new Integer(2));
for (int i = 0; i < al.size(); i++) {
sum += (Integer) al.get(i);
}
System.out.println(sum);
}

}

沒有留言:

張貼留言