how to convert an Array to a linked list in Java

Michael Fogarty :

I am a fairly new Java programmer and I am currently learning about converting lists to arrays. The problem that I am having is that when I try to link the list the output I am getting is not the same as what is in the array. The linked list output is all null values while the array has random values as it should. Here is my code:

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);
        }
    }
}

And here is the output:

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
John3136 :

Move List<Integer> linkList = new LinkedList<> (Arrays.asList(numbers)); to after where you populate the array otherwise your linked list is just a list of default values.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85797&siteId=1