ArrayList类的toArray()方法以正确的顺序(从第一个到最后一个元素)返回一个包含此列表中所有元素的数组。这充当了基于数组的API和基于集合的API之间的桥梁。
import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { ArrayList<Integer> arrlist = new ArrayList<Integer>(5); arrlist.add(20); arrlist.add(40); arrlist.add(10); arrlist.add(15); arrlist.add(25); for (Integer number : arrlist) { System.out.println("Number = " + number); } Object[] ob = arrlist.toArray(); System.out.println("从头到尾打印元素:"); for (Object value : ob) { System.out.println("Number = " + value); } } }
输出结果
Number = 20 Number = 40 Number = 10 Number = 15 Number = 25 从头到尾打印元素: Number = 20 Number = 40 Number = 10 Number = 15 Number = 25