toArray() 方法的作用是什么?
java.util.The ArrayList 类的 toArray() 方法返回包含此列表中所有元素(从第一个到最后一个元素)的数组。这充当了基于数组和基于集合的 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("Printing elements from first to last:"); for (Object value : ob) { System.out.println("Number = " + value); } } }
输出
Number = 20 Number = 40 Number = 10 Number = 15 Number = 25 Printing elements from first to last: Number = 20 Number = 40 Number = 10 Number = 15 Number = 25
广告