Getting a random player/string from ArrayList or Hashmap?

Discussion in 'Plugin Development' started by FabeGabeMC, May 6, 2014.

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

    FabeGabeMC

    I'm really curious how this works and what I've been thinking is to loop through all the players in the list.

    Thought Code:
    Code:java
    1. int i = 0;
    2. for(Player p : <list>){
    3. if(i < <list>.length - (<list>.length - 1)){
    4. <list>.add(p.getName());
    5. }
    6. }
    7. //<list> is representing a list. Can be anything.


    Would anyone tell me a concept/idea for the code that would be used or a way to get around this?

    Thanks,
    Gabe
     
  2. Offline

    Jogy34

    Code:java
    1.  
    2. Random rnd = new Random();
    3.  
    4. //Random item from a list
    5. list.get(rnd.nextInt(list.size()));
    6.  
    7. //Random item from an array
    8. array[rnd.nextInt(array.length)];
    9.  

    Hope that's what you're looking for.

    As a side note, don't save player objects, it causes memory leaks. Save their name or UUID and retrieve them from the server using that.
     
  3. Offline

    mickedplay

    Jogy34 And how do you get player p?
     
  4. Offline

    Garris0n

    ...exactly like he said to.
     
  5. Offline

    FabeGabeMC

    Jogy34 Obviously I would store them in a list of strings.
    List<String> players = new ArrayList<String>();
    Also I will test.
    Garris0n Exactly ^^
     
  6. Offline

    AoH_Ruthless

  7. Offline

    Jogy34

    If you have a list of size 5, list.size() will return 5, which will cause the Random object to return a number from 0 to 4, hence generating 5 numbers not 6.
     
  8. Offline

    Garris0n

    Huh?
     
  9. Offline

    FabeGabeMC

  10. Offline

    Jogy34

    Getting a random value out of a list the way I showed works perfectly fine, I use it all the time. The only thing you have to worry about is if the array or list is of size 0. Then the nextInt() method will yell at you saying 'n must be positive'
     
  11. Offline

    1Rogue


    nextInt() returns 0 inclusive, maximum exclusive. Passing "5" would return 0, 1, 2, 3, or 4.
     
  12. Offline

    ZeusAllMighty11

    Oops, sorry :p
     
    AoH_Ruthless likes this.
Thread Status:
Not open for further replies.

Share This Page