Getting 5 elements from an ArrayList without duplicates.

Discussion in 'Plugin Development' started by WolfMage1, Jun 6, 2016.

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

    WolfMage1

    What I currently have is an ArrayList containing arenas that are downloaded (their data) from the database.

    What I'm trying to achieve is selecting 5 random arenas from that list without duplicates.

    The only way I can think if which has the possibility of duplicates is using java's Random util.

    //This is the only way I can think of doing it.

    Code:
    List<Arena> choices=new ArrayList<>();
    for(int i=1;i=<5;i++){
        choices.add(getArenas().get(new Random().nextInt(getArenas.size())));
    }
    
     
  2. Offline

    Zombie_Striker

    @WolfMage1
    Here is what you should do:
    1. Store that arena instance somewhere.
    2. If 'choices' contains that arena, i--; (meaning it will loop one more time)
    3. If 'choices' does not contain the arena, then add it.
     
  3. Offline

    ILoveCode

    Why dont you use a Set?
     
    Zombie_Striker likes this.
  4. Offline

    WolfMage1

    How would this change anything from the way @Zombie_Striker said.
     
  5. Offline

    Lordloss

    well, you wouldnt have to check if it allready contains the element, just make sure it stops after 5. Its not a big difference.
     
  6. Offline

    Xerox262

    @WolfMage1 Sets don't allow duplicates, so you could just loop until you ran out of things to loop through or until there are 5 elements in the set.
     
Thread Status:
Not open for further replies.

Share This Page