0

I am Rookie. I have to select randomly different elements from an ArrayList which has an array of strings. I tried couple different ways but it is selecting the same array every time.Here are the ways I tried.

 public static void RandomSchedules(ArrayList<String[]> list)
{
    Random randomizer = new Random();
    for(int i=1; i<11; i++)
   {

    String[] random = list.get(new Random().nextInt(list.size()));
    System.out.println("Random Schedule " +  ":" + Arrays.toString(random));
    }
}

I also tried this in the above code.

   String[] random = list.get(randomizer.nextInt(list.size()));

But the result is same.

This is the other approach I have tried from Stack Overflow

 public static List<String[]> pickNRandom(ArrayList<String[]> lst, int n) {
List<String[]> copy = new LinkedList<String[]>(lst);
Collections.shuffle(copy);
return copy.subList(0, n);
 }

I am calling the above function as,

    List<String[]> randomPicks = pickNRandom(lst, 10);

Could anyone guide me how to get different elements.

2
  • Sounds to me like you might have duplicate arrays. Did you check the contents? Commented Oct 31, 2017 at 18:35
  • Please provide a minimal reproducible example. Commented Oct 31, 2017 at 18:42

1 Answer 1

3

You don't use your randomizer object, but create a new one each time in the loop. So use the one you created (avoiding the new Random call everytime). Try:

public static void RandomSchedules(ArrayList<String[]> list)
{
    Random randomizer = new Random(System.currentTimeMillis());
    for(int i=1; i<11; i++)
    {
        String[] random = list.get(randomizer.nextInt(list.size()));
        System.out.println("Random Schedule " +  ":" + Arrays.toString(random));
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

What is your input list? If it just one String [] (list.size() == 1), then it will do that, but multiple string[] in your list will yield variable outputs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.