There is a need to create a HashSet collection with 20 numbers from 0 to 20. When you create using the code written below, each time a collection is created with a random number of elements from random numbers. Tell me, please, why so? Indeed, in the cycle indicated the creation of 20 elements.
package level8; import java.util.*; public class task182_lev8_lec08 { public static HashSet<Integer> createSet() { int a = 20; HashSet<Integer> integerHashSet = new HashSet<>(); for (int i = 0; i < 20; i++){ double random = Math.random() * a; integerHashSet.add((int) random); } return integerHashSet; } public static void main(String[] args) { System.out.println(createSet()); } }
Setcan contain only unique elements. If several identical numbers are created in the loop, only one will be saved. - Sergey Gornostaev