Java AbstractCollection 類中的 toArray(T[] a) T 方法


Java AbstractCollection 中的 toArray() 和 toArray(T[] arr) 的區別在於,這兩個方法都返回一個包含此集合中所有元素的陣列,但後者有一些附加特性,即,返回陣列的執行時型別是指定陣列的型別。

語法如下

public <T> T[] toArray(T[] arr)

其中,arr 是將此集合中的元素儲存到的陣列。

要使用 Java 中的 AbstractCollection 類,匯入以下包

import java.util.AbstractCollection;

以下是 Java 中 AbstractCollection toArray() 方法實現示例

示例

 演示

import java.util.ArrayList;
import java.util.AbstractCollection;
public class Demo {
   public static void main(String[] args) {
      AbstractCollection<Object> absCollection = new ArrayList<Object>();
      absCollection.add("HDD");
      absCollection.add("Earphone");
      absCollection.add("Headphone");
      absCollection.add("Card Reader");
      absCollection.add("SSD");
      absCollection.add("Pen Drive");
      System.out.println("AbstractCollection = " + absCollection);
      System.out.println("Count of Elements in the AbstractCollection = " + absCollection.size());
      String[] myArr = new String[5];
      myArr = absCollection.toArray(myArr);
      System.out.println("Array returning the elements of this collection = ");
      for (int i = 0; i < myArr.length; i++)
      System.out.println(myArr[i]);
   }
}

輸出

AbstractCollection = [HDD, Earphone, Headphone, Card Reader, SSD, Pen Drive]
Count of Elements in the AbstractCollection = 6
Array returning the elements of this collection =
HDD
Earphone
Headphone
Card Reader
SSD
Pen Drive

更新時間:2019 年 7 月 30 日

94 條瀏覽量

開啟你的 職業生涯

完成課程,獲取認證

開始
廣告
© . All rights reserved.