toArray()
和Java AbstractCollection中的toArray(T [] arr)之间的区别在于,这两种方法都返回一个包含此集合中所有元素的数组,但是后者具有一些其他功能,即,返回数组的运行时类型是指定的数组。
语法如下
public <T> T[] toArray(T[] arr)
在这里,arr是要将此集合的元素存储到的数组。
要使用Java中的AbstractCollection类,请导入以下包
import java.util.AbstractCollection;
以下是toArray()
在Java中实现AbstractCollection方法的示例
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