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

更新於: 18-6-2024

18K+ 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告