Randomising of a String

Discussion in 'Spigot Plugin Development' started by RapidTurtle, Jul 2, 2016.

  1. Hello,

    I'm making a small plugin for friends on a friend server. I am wondering how I would go upon getting say an arraylist of memes and then when a player executes /meme it will send them a message of a random meme.
    I know the basics like the command executor and stuff, just could i randomise it.

    Thanks Luka
  2. Use List#get to with a number between 0 and the size of the list. You can use ThreadLocalRandom.current() or just use a Random object

    Code (Java):
    private String getRandomMeme() {
         return memes.get(ThreadLocalRandom. current().nextInt(memes.size()) /* Generates a random number between 0 and the size of the list */);
    #2 Trophonix, Jul 2, 2016
    Last edited: Jul 2, 2016
    • Winner Winner x 1
  3. Not trying to be pest but, i don't really get it bc noob
  4. Well, if your meme list is called "memes" then the code I gave will do exactly what you said. Do some research about randoms in java.
  5. Just to note, you do not want to be creating a new Random instance every time you execute the command.
    First of all, it causes the numbers to not be so random, and then it's heavy on the garbage collector and the ram - causing performance issues.
    You would want to create a private class variable of type Random, initialize it in the constructor of the class, and then reuse it.
    For example:
    Code (Text):
    public class MyClass{
    private Random myRandom;

    public MyClass(){
    myRandom = new Random();

    public int getRandomInt(){
    return myRandom.nextInt(10);
  6. Good point. I think initializing it inside the constructor is pointless, though. Alternatively you can use ThreadLocalRandom.current()
  7. You were right on the creating a new Random instance not being that good for performance, but it has nothing to do with RAM or the GC.
  8. whenever you create a new object, the memory manager allocates space for it on the heap.
    The garbage collector keeps track of this and when an object no longer has any references or when it is destroyed, the garbage collector has to deallocate that space in the heap so that it can be used for other objects. This has some overhead and takes some time, therefore, decreasing performance the more objects you have.
    The heap is also stored in RAM, so, if you make a ton of objects, more RAM is used.
  9. For what it's worth, I edited my post :p
  10. @123099 I am aware of all of that, but that makes it the same as allocating any other object. It's not that important compared to the performance impact is has, as it's retrieving the system's current time every time you create it and don't specify a seed.
  11. Thank you so much :)
  12. MiniDigger


    that would be overkill as op does not want to shuffle it but only get ONE random element. shuffle needs to switch many elements in the list which can be quite a heavy task for large lists.