Randomization in Java

I have 4 lines for representing people and 4 lines for representing names.

I try to randomize them so that every time I run my application my four people will have different names, but no one can have the same name at runtime.

Example:

String person_one; String person_two; String person_three; String person_four; String name_one = "Bob"; String name_two = "Jane"; String name_three = "Tim"; String name_four = "Sara"; 

Hope this makes sense.

+4
source share
2 answers

You can use Collections.shuffle () :

 List<String> names = new ArrayList<String>(); names.add("Bob"); names.add("Jane"); names.add("Tim"); names.add("Sara"); Collections.shuffle(names); person_one = names.get(0); person_two = names.get(1); person_three = names.get(2); person_four = names.get(3); 
+9
source
+2
source

Source: https://habr.com/ru/post/1440324/


All Articles