Java AbstractCollection类的toArray()方法
在toArray()
该班类AbstractCollection方法用来返回这个集合中的元素。元素以数组形式返回。
语法如下
public Object[] toArray()
要使用Java中的AbstractCollection类,请导入以下包
import java.util.AbstractCollection;
首先,声明AbstractCollection并添加一些元素
AbstractCollection<Object> absCollection = new ArrayList<Object>(); absCollection.add("Laptop"); absCollection.add("Tablet"); absCollection.add("Mobile"); absCollection.add("E-Book Reader");
现在,使用该toArray()
方法以数组形式返回元素
Object[] myArr = absCollection.toArray();
以下是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("Laptop"); absCollection.add("Tablet"); absCollection.add("Mobile"); absCollection.add("E-Book Reader"); absCollection.add("SSD"); absCollection.add("HDD"); System.out.println("AbstractCollection = " + absCollection); System.out.println("Count of Elements in the AbstractCollection = " + absCollection.size()); Object[] myArr = absCollection.toArray(); System.out.println("Array returning the elements of this collection = "); for (int i = 0; i < myArr.length; i++) System.out.println(myArr[i]); } }
输出结果
AbstractCollection = [Laptop, Tablet, Mobile, E-Book Reader, SSD, HDD] Count of Elements in the AbstractCollection = 6 Array returning the elements of this collection = Laptop Tablet Mobile E-Book Reader SSD HDD