1

I have this empty Array List. I wanted to add 6 randomly generated integers (1 to 6) but I don't want it to be duplicated. Somehow I cannot manage to create loop for that. I keep getting duplicated values, and even the size of Array List keep changing. here is my code. Thanks in advance.

    ArrayList al = new ArrayList();

    int rnd = new Random().nextInt(6)+1;

    while(!(al.contains(rnd))){

                for(int i=0; i<=5; i++){

                    al.add(rnd);
                    rnd = new Random().nextInt(6)+1;

                }

                rnd = new Random().nextInt(6)+1;

    }

    System.out.print(al);
David Hash
  • 11
  • 1
  • Have a look at the .contains() method of the `ArrayList`. – smsnheck Nov 15 '16 at 07:39
  • 1
    Why don't you use `Set`? Which doesn't allow duplicates – Pradeep Simha Nov 15 '16 at 07:40
  • Add to `Set` and then convert to `ArrayList`. – Maroun Nov 15 '16 at 07:42
  • Put the numbers 1-6 into the list and shuffle it. – Andy Turner Nov 15 '16 at 07:48
  • Here is the thing. When I use Set ( HashSet) it is giving the output in ascending order because the integer size is too small. it is always giving [1,2,3,4,5,6]. I believe that's how HashSet works. But, I need unordered way. Thanks for the replies though. I could use shuffle(), but I need it to first add a random integer in my range, then create another random number add it if its not already in the list, and repeat it till 6. No shuffling. – David Hash Nov 15 '16 at 09:08

1 Answers1

0

Get all the values in LIST and then put that list in the Set (duplicates are not allowed in Set.)

Khusboo
  • 117
  • 1
  • 1
  • 9