dimanche 12 août 2018

Retrieve random key from Hashtable

Well, i think everything is in the title...

But to make it more clear: i have a Hashtable, where the keys are Strings (more precisely: user names) and the values are a personal class, let's say UserData. So obviously i use this table to retrieve some UserData knowing the user name; but sometimes i would like to take a random user name.

That's why i need to find a way to select a random key in my Hashtable.

I've tried that:

            Random random = new Random();
            int randomIndex = random.nextInt(myHashtable.size())-1;
            String[] names = null;
            myHashtable.keySet().toArray(names);
            String randomUser = names[randomIndex];
            System.out.println(randomUser);

But it doesn't work (i get an error for a bad use of Random, sorry i don't have the details right now)




Aucun commentaire:

Enregistrer un commentaire