views:

537

answers:

3

Hi everyone,

I have few files which I put in array. I shuffle the files so that it can be displayed in random order. How to know that array index 0 is actually image1.txt or image2.txt or image3.txt? Thanks in advance.

String[] a = {"image1.txt","image2.txt","image3.txt"};
List<String> files = Arrays.asList(a);
Collections.shuffle(files);
+3  A: 

I'm not sure what you are trying to do.

To access the first element of the shuffled list, use files.get(0).

If you want to know where each element is gone, I suggest you take another approach to it. Create a list of integers from 0 to a.length() - 1, inclusive and shuffle that list. Then manually permute the array a to a new collection.

Mehrdad Afshari
Yeah it's java. The Collections.shuffle gives it away.
JaredPar
@JaredPar: camelCasing is also a huge hint.
Mehrdad Afshari
@Mehrdad, I usually see Camel casing as a typo :)
JaredPar
@JaredPar: Lol! It was the same for me until a couple days ago I had to work on umbarco CMS's source which is full of camelCasing :)
Mehrdad Afshari
A: 

I'm not really sure what you're trying to do, but if you just need to know what index each String is at you can use the List.indexOf(Object) method. So to find the index of "image1.txt" you could do

int index = files.indexOf(a[0]);
Greg
A: 

INCORRECT - see explanation

Note: Arrays.asList() will create a NEW list with the contents of the passed array. The original array will not be modified at all when you use Collections.shuffle().

Explanation

Peter has correctly pointed our that Arrays.asList() does NOT make a copy. The returned list is "write-through" back to the original array. Shuffling the list will shuffle the contents of the original array. Also worth noting that the list is immutable (new elements cannot be added) but typically I find that the use of Arrays.asList() involves immutable lists anyway.

files.get(0); // get the first elements in shuffled list, random

// as greg said
int index = files.indexOf(a[0]); // find out where "image1.txt" is in the list
files.get(index); // get "image1.txt" back from the list
basszero
Thanks a lot. Thats really help me.
Jessy
Actually Arrays.asList() is just a wrapper for the original array, it doesn't take a copy so changes to one change both.
Peter Lawrey
I can't believe I overlooked that! Thanks Peter! Not sure how useful my answer is now ...
basszero