Home > front end >  What is the best/most efficient Java collection to use to pull a random value?
What is the best/most efficient Java collection to use to pull a random value?

Time:07-20

I am creating an NPC generator, in which all their attributes are randomly pulled from their respective collection of possible values. What would be the most efficient collection to use to store the possible values in order to randomly pull a value from or is there no real difference?

CodePudding user response:

An ArrayList gives you the best performance for randomly choose a value because it has O(1) access time.

See here for a explanation: https://stackoverflow.com/a/322742/7142748

CodePudding user response:

I am creating an NPC generator

If by saying poll you mean only accessing a random element, and not removing it, you can use a plain ArrayList to store your objects.

Random rand = new Random();
List<NPC> npcs = new ArrayList<>(); // fields

NPC npc = npcs.get(rand.nextInt(npcs.size())); // resides in a method

CodePudding user response:

You can use Math.random multiply with the size of the list to get the random value

List<Integer> list = new ArrayList<>();
int index = (int) (Math.random() * list.size());
NPC npc = list.get(index);
  • Related