[UTIL] Get a Random Object

Discussion in 'Resources' started by iKeirNez, Jun 28, 2013.

Thread Status:
Not open for further replies.
  1. Recently I've been working on a mini-game plugin for someone and I had to get random locations and if possible make each player spawn at a different location. I came up with this method, basically you pass in 2 lists, the first list contains all the possible java objects and the second list contains all the used java objects.

    1. public static <T> T getUnusedObject(List<T> objects, List<T> usedObjects){
    2. Random random = new Random();
    4. // If all objects have been used, pick a random one
    5. if (usedObjects.containsAll(objects)){
    6. return objects.get(random.nextInt(objects.size()));
    7. }
    9. // Keep running this code until we find an object we can use
    10. T randomObject = objects.get(random.nextInt(objects.size()));
    11. while (usedObjects.contains(randomObject)){
    12. randomObject = objects.get(random.nextInt(objects.size()));
    13. }
    15. return randomObject;
    16. }

    Again this works for any type of java object (Strings, Integers, Locations, ItemStacks etc)
    Example Usage:
    The below example usage would work for a mini-game type plugin.
    1. List<Location> usedLocations = new ArrayList<Location>();
    2. for (Player player : Bukkit.getOnlinePlayers()){
    3. if (getPlayers().contains(player)){
    4. Location spawn = Utils.getUnusedObject(getSpawnLocations(), usedSpawns);
    5. usedLocations.add(spawn);
    6. player.teleport(spawn, TeleportCause.PLUGIN);
    7. }
    8. }

    Enjoy :)
    (Also first post in ages, I hope to become more active here again)
  2. Offline


    Isn't a HashMap<Object,Boolean> a better solution here?

  3. The way I used was more convenient for what I was using it for. However that would be a better option in most other cases.
  4. Offline


    Maybe an example would go good with this thread? I'm in the process of making 3 mini-game plugins, and I want to see if this would be a good thing to use. Thanks :)
  5. Added example code
Thread Status:
Not open for further replies.

Share This Page