LinkedList of Arrays .. All elements get the value of the last element

Viewed 28

I'm trying to fill a LinkedList of Arrays using For loop but the result is weird: All elements outside my 'for' loop get the value of the last element! However, when I do the same thing with a LinkeList of Integer this time it works all elements get its "real value". So my question is: Why it works with LinkedList of Integer but it didn't work with arrays ??

    public static void main(String[] args) {
        LinkedList<Integer[]> listOfArrays = new LinkedList<Integer[]>();
        LinkedList<Integer> listOfInt = new LinkedList<Integer>();
        Integer[] array = new Integer[2];

            for(int i = 0; i <= 2; i++) {
                array[0] = i;
                array[1] = i+1;
                listOfArrays.add(array);
                listOfInt.add(i);
                System.out.println("Result 1 verifying current array: " + Arrays.toString(array));
                System.out.println("Result 2 verifying last added member of my list of arrays: " + Arrays.toString(listOfArrays.getLast()) + "\n");
                }

            System.out.println("\nResult 3 verifying the same fucking list outside 'for' loop");
        for (int k = 0; k<listOfArrays.size(); k++) 
            System.out.println("element number " + k + ": " + Arrays.toString(listOfArrays.get(k)));

            System.out.println("\nResult 4 verifying integer list outside 'for' loop");
        for (int k = 0; k<listOfInt.size(); k++) 
            System.out.println("element number " + k + ": " + (listOfInt.get(k).toString()));
}
1 Answers

You are resuing the same array and overwriting its elements in each iteration of the loop. Therefore, all the elements of the list are in fact the same array, and thus they all have the data, regardless of the element you're looking at. Instead, you should create a new array in each iteration:

for (int i = 0; i <= 2; i++) {
    Integer[] array = new Integer[2];

    array[0] = i;
    array[1] = i+1;
    listOfArrays.add(array);
    listOfInt.add(i);
}
Related