0

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?

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46

3 Answers3

1

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

jhueg
  • 483
  • 2
  • 13
1

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
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
0

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);
0xh3xa
  • 4,801
  • 2
  • 14
  • 28