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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP