如何在 Java 中将数组转换为链表



我是一个相当新的Java程序员,我目前正在学习将列表转换为数组。我遇到的问题是,当我尝试链接列表时,我得到的输出与数组中的输出不同。链表输出都是空值,而数组具有应有的随机值。 这是我的代码:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class InsertingElements {
public static void main(String[] args) {
Integer[] numbers = new Integer[25];
List<Integer> linkList = new LinkedList<>(Arrays.asList(numbers));
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (int) (Math.random() * 100 + 1);
}
System.out.println("Numbers Generated: " + Arrays.toString(numbers));
numbers = linkList.toArray(new Integer[linkList.size()]);
System.out.println("Numbers: ");
for (Integer number : numbers) {
System.out.println(number);
}
}
}

这是输出:

Numbers Generated: [92, 61, 25, 8, 48, 80, 85, 89, 53, 18, 48, 38, 48, 
41, 93, 94, 24, 73, 83, 21, 18, 52, 3, 14, 10]
Numbers: 
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null

List<Integer> linkList = new LinkedList<> (Arrays.asList(numbers));移动到填充数组的位置之后,否则链表只是一个默认值列表。

试试这个

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class InsertingElements {
public static void main(String[] args) {
Integer[] numbers = new Integer[25];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (int) (Math.random() * 100 + 1);
}
List<Integer> linkList = new LinkedList<>(Arrays.asList(numbers));
System.out.println("Numbers Generated: " + Arrays.toString(numbers));
numbers = linkList.toArray(new Integer[linkList.size()]);
System.out.println("Numbers: ");
for (Integer number : numbers) {
System.out.println(number);
}
}
}
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class InsertingElements {
public static void main(String[] args) {
Integer[] numbers = new Integer[25];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (int) (Math.random() * 100 + 1);
}
List<Integer> linkList = new LinkedList<>(Arrays.asList(numbers));
System.out.println("Numbers Generated: " + Arrays.toString(numbers));
numbers = linkList.toArray(new Integer[linkList.size()]);
System.out.println("Numbers: ");
for (Integer number : numbers) {
System.out.println(number);
}
}
}

相关内容

  • 没有找到相关文章

最新更新