How to drop a random item from a list?

Discussion in 'Spigot Plugin Development' started by digdiggydigger, Apr 18, 2017.

  1. Hi Spigot,

    At the moment I'm trying to make it so that after a certain amount of time after a certain block has been placed down, a random item will be dropped at the blocks position.. I've got the items list setup but I'm not sure how to get a random item from that list?

    Code (Text):
        public static ArrayList<Material> randomItems() {
           
            ArrayList<Material> items = new ArrayList<Material>();
            items.add(Material.LEATHER_HELMET);
            items.add(Material.LEATHER_CHESTPLATE);
            items.add(Material.LEATHER_LEGGINGS);
            items.add(Material.LEATHER_BOOTS);
            return items;
        }
     
  2. Use a random number generator to generate a random number preferably of the number of items in the array, and then use that to select the item from the array
     
  3. Random class?
    Get a random and world.dropItem
     
  4. what about not static
    what about a constant list
    what about threadlocalrandom
     
    • Funny Funny x 1
  5. Code (Java):
    ArrayList#get(
      ThreadLocaleRandom.current().nextInt(0, ArrayList#size() - 1)
    );
    That negative one is important because the size method excludes 0, which is an index. So an array where index 0, 1, and 2 is present, size will return 3 (1, 2, 3). So if you were to land at the last number, the program wouldn't throw an ArrayIndexOutOfBoundsException exception.

    References:
     
    #6 ExpDev, Apr 18, 2017
    Last edited: Apr 18, 2017
    • Agree Agree x 1
  6. Yeah i was going to do something similar..

    yeah i know how to do the dropping part, but thanks.

    what about something helpful?

    Your helpful aren't you? lol :rolleyes:

    Actually helpful thank you.:D:D
     
  7. he is
    he linked you to your solution
    threadlocalrandom is helpful
    if you know java/kotlin/clojure/scala/what the fuck you use it'll end well
     
    • Like Like x 1
  8. Use a Linked list and shuffle it:

    Code (Text):
    LinkedList<T> items = new LinkedList<>();
    Collections.suffle(items);
    items.pop(); //It also removes the item from the list
     
    • Informative Informative x 1