AbstractSequentialList 中 toArray(T[]) 方法在 Java 中
toArray() 和 toArray(T[] arr) 之间的区别在于,这两种方法都返回一个包含此集合中所有元素的数组,但是后者有一些附加功能,即返回数组的运行时类型就是指定数组的类型。
语法如下
public <T> T[] toArray(T[] arr)
此处,arr 是用于存储此集合元素的数组,
要使用 Java 中的 AbstractSequentialList 类,你需要导入以下包
import java.util.AbstractSequentialList;
以下是一个在 Java 中实现 AbstractSequentialList toArray() 方法的示例
示例
import java.util.LinkedList; import java.util.AbstractSequentialList; public class Demo { public static void main(String[] args) { AbstractSequentialList<Integer> absSequential = new LinkedList<>(); absSequential.add(210); absSequential.add(290); absSequential.add(350); absSequential.add(490); absSequential.add(540); absSequential.add(670); absSequential.add(870); System.out.println("Elements in the AbstractSequentialList = "+absSequential); Integer[] strArr = new Integer[5]; strArr = absSequential.toArray(strArr); System.out.println("Array = "); for (int i = 0; i < strArr.length; i++) System.out.println(strArr[i]); ; } }
输出
Elements in the AbstractSequentialList = [210, 290, 350, 490, 540, 670, 870] Array = 210 290 350 490 540 670 870
让我们再看一个示例,其中数组大小大于元素总数
示例
import java.util.LinkedList; import java.util.AbstractSequentialList; public class Demo { public static void main(String[] args) { AbstractSequentialList<Integer> absSequential = new LinkedList<>(); absSequential.add(210); absSequential.add(290); absSequential.add(350); absSequential.add(490); System.out.println("Elements in the AbstractSequentialList = "+absSequential); Integer[] strArr = new Integer[7]; strArr = absSequential.toArray(strArr); System.out.println("Array = "); for (int i = 0; i < strArr.length; i++) System.out.println(strArr[i]); ; } }
输出
Elements in the AbstractSequentialList = [210, 290, 350, 490] Array = 210 290 350 490 null null null
广告