Solved HashSet Question

Discussion in 'Plugin Development' started by crushh87, Apr 8, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    crushh87

    How would I go about picking a random player from a hashset? I have looked all over for an example but I could not find one that really helped.

    Thank you,
    God bless.
     
  2. I do it like this:
    Code:java
    1. List<Player> playerList = new ArrayList<Player>(yourHashSet);
    2. Collections.shuffle(playerList);
    3. Player randomPlayer = playerList.get(0);

    There may be better methods, but I got used to this one.

    You could also use:
    Code:java
    1. List<Player> playerList = new ArrayList<Player>(yourHashSet);
    2.  
    3. Player randomPlayer = playerList.get(new Random().nextInt(playerList.size()));


    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 31, 2016
    crushh87 likes this.
  3. Offline

    crushh87

    Throwing me errors under
    List:
    The type List is not generic; it cannot be parameterized with arguments <Player>

    new ArrayList<Player>(pl.inLobby);
    The constructor ArrayList<Player>(Set<String>) is undefined
     
  4. Offline

    ZeusAllMighty11

    Hellsing

    I don't know how efficient shuffle is, but it looks better than what I do.


    Code:
    public Player randomPlayer(List<String>list){
         int select = new Random().nextInt(list.size());
         Player p = Bukkit.getServer().getPlayer(list[select]);
         return p;
    }
    You should never store a Player object.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 31, 2016
    crushh87 likes this.
  5. Offline

    crushh87

    Doing it for both methods

    Solved thanks
    TheGreenGamerHD Hellsing

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 31, 2016
  6. Offline

    Codisimus

    Also perhaps not use a HashSet, it depends on wut you are using it for.
     
  7. Offline

    crushh87

    Ermmm.... One more question:

    Now how do I get the other players that were not chosen at random?

    So

    Player1 -> Taken out of of hashset

    Player2
    & -> Still remain
    Player3

    How would I go and get Player2 & Player3?

    Thanks
     
  8. Offline

    Codisimus

    remove the chosen Player, then the collection will hold all of the not chosen players.
     
  9. Offline

    crushh87

    Oops forgot to mention I figured it out.

    [Offtopic]My 800th Post :D[/Offtopic]
     
Thread Status:
Not open for further replies.

Share This Page