java array shuffling

I've noticed that the underlying int array is getting changed given the way the list is being created:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;


public class Shuffling {

    static Integer[] intArr = {1, 2, 3, 4, 5};
    static Random random = new Random(7);
    public static void main(String[] args) {

        List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArr));
        Collections.shuffle(intList, random);
        System.out.println("List after shuffling: " + intList);
        System.out.println("intArr: " + Arrays.toString(intArr));
        //OUTPUT:
        //List after shuffling: [5, 4, 1, 3, 2]
        //intArr: [1, 2, 3, 4, 5]


        List<Integer> intList2 = Arrays.asList(intArr);
        Collections.shuffle(intList2, random);
        System.out.println("List2 after shuffling: " + intList2);
        System.out.println("intArr: " + Arrays.toString(intArr));
        //OUTPUT:
        //List2 after shuffling: [5, 3, 4, 2, 1]
        //intArr: [5, 3, 4, 2, 1]
    }
}

Why is that happening?

Answers


Arrays.asList() constructs a special list that is backed by the original array.

Which is why the list does not support the (optional) add() and remove() methods from the Collection interface (they wouldn't be possible using an array).

Interestingly, the returned class is called ArrayList, although it is not to be confused with java.util.ArrayList.

System.out.println(
    Arrays.asList("1", "2", "3")
    .getClass().getName()
);
// Output: java.util.Arrays$ArrayList

Need Your Help

Is it possible to set a block as a target on a UIButton?

iphone objective-c

I need to send extra arguments to a method on button press, but can't find a way to make addTarget send a selector to do that.

Highlighting glossary terms inside a HTML document

javascript python highlighting glossary glossaries

We have a glossary with up to 2000 terms (where each glossary term may

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.