-5

How to randomize ArrayList.add(Object)?

Random random = new Random();

ArrayList arrayList = new ArrayList();
arrayList.add((Object)("one"));
arrayList.add((Object)("two"));
arrayList.add((Object)("three"));
arrayList.add((Object)("four"));
arrayList.add((Object)("five"));
PrR3
  • 1,250
  • 1
  • 18
  • 26
Mihir
  • 557
  • 1
  • 6
  • 28
  • what does `randomize ArrayList.add` mean? – njzk2 Apr 02 '14 at 19:08
  • How can i randomize above code? not sure how else could i explain? – Mihir Apr 02 '14 at 19:09
  • @njzk2, I believe Mihir wants to insert new items at a random position in the ArrayList. – Bryan Herbst Apr 02 '14 at 19:10
  • 1
    [Randomise after adding the values](http://stackoverflow.com/questions/4228975/how-to-randomize-arraylist) – PrR3 Apr 02 '14 at 19:12
  • Thanks PrR3 - i was looking for "Collections.shuffle(arrayList); – Mihir Apr 02 '14 at 19:16
  • yes, my crystal ball even works... ;) – PrR3 Apr 02 '14 at 19:18
  • Guys i'm getting -5 points for this question, how else one could ask this question? – Mihir Apr 02 '14 at 19:19
  • Most of the downvotes are likely because this question is easily solvable with a little bit of research, and a good StackOverflow question demonstrates shows that you have made an attempt to research your question before asking. – Bryan Herbst Apr 02 '14 at 19:25
  • i did know how to randomize regular array, but didn't know how to randomize above array. Oh well, next time will be more careful :) thanks – Mihir Apr 02 '14 at 19:28
  • downvotes come from this question being solvable by googling `random arraylist` and a few seconds – njzk2 Apr 02 '14 at 20:26

1 Answers1

1

The easiest method of accomplishing this is to call Collections.shuffle(List, Random) on your ArrayList after you have inserted all of the elements.

If you really want to do this as you insert the items instead, you can use add(int, E) to specify the position at which you need to insert the item. Something like this would do:

arrayList.add(random.nextInt(arrayList.size()), "MyString");
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120