Java ArrayList toArray()方法

java.util.ArrayList.toArray() 方法返回ArrayList的数组形式,返回的是Object[]。

1 语法

public Object[] toArray()

2 参数

3 返回值

返回ArrayList的Object[]对象数组。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.ArrayList.toArray()方法的例子
 */
import java.util.ArrayList;

public class Demo {
    public static void main(String[] args) {

        // create an empty array list with an initial capacity
        ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

        // use add() method to add values in the list
        arrlist.add(20);
        arrlist.add(40);
        arrlist.add(10);
        arrlist.add(15);
        arrlist.add(25);

        // let us print all the elements available in list
        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

 

热门文章

优秀文章