简体   繁体   中英

How can I add 100 random elements to an empty array with duplicates?

In this code, I'm shuffling 100 random elements instead of adding 100 random elements with duplicates, and returning 10 unique keys. How can I do that?

public static void main(String[] args) {

    ArrayList<Integer> uniqueKeys = new ArrayList<Integer>();
    for (int i = 0; i < 101; i++) {
        uniqueKeys.add(new Integer(i));
    }
    Collections.shuffle(uniqueKeys);
    for (int i = 0; i < 10; i++) {
        System.out.println(uniqueKeys.get(i));
    }
}

I suggest using a combination of Set and Random. Using Set, you will get rid of duplicates. Using Random, you will get (pseudo) random numbers.

final int KEYS_COUNT = 100;
final int MAX_KEY_VALUE = 1000;

Set<Integer> setOfKeys = new HashSet<>();
Random random = new Random();

while (setOfKeys.size() <= KEYS_COUNT) {
    setOfKeys.add(random.nextInt(MAX_KEY_VALUE));
}

The Set setOfKeys will contain 100 unique random numbers with their values less then 1000. You can then use toArray() method to make array from the Set.

If you make KEYS_COUNT equal to MAX_KEY_VALUE , the values won't be much random, they will be only shuffled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM