Java 程序将列表转换为数组


List 对象提供一个称为 toArray() 的方法。此方法接受一个空数组作为参数,将当前列表转换为数组并放入给定的数组中。要将 List 对象转换为数组 -

  •  创建一个 List 对象。
  •  向其添加元素。
  •  使用已创建的 ArrayList 的大小创建一个空数组。
  •  使用 toArray() 方法 将列表转换为数组,传递上述创建的数组作为参数。
  •  打印数组的内容。

示例

在线演示

import java.util.ArrayList;
public class ListToArray {
   public static void main(String args[]){
      ArrayList<String> list = new ArrayList<String>();
      list.add("Apple");
      list.add("Orange");
      list.add("Banana");

      System.out.println("Contents of list ::"+list);
      String[] myArray = new String[list.size()];
      list.toArray(myArray);

      for(int i=0; i<myArray.length; i++){
         System.out.println("Element at the index "+i+" is ::"+myArray[i]);
      }
   }
}

输出

Contents of list ::[Apple, Orange, Banana]
Element at the index 0 is ::Apple
Element at the index 1 is ::Orange
Element at the index 2 is ::Banana

更新日期:2024 年 6 月 18 日

18K+ 浏览量

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.