0

The method below is the method I am using to populate my array. However I wish to return a random deals_informationobject from my ArrayList of type Deals_Information but am not quite sure how.

    public void populateArray() {

    databaseReference.child("FruitDeals").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Iterable<DataSnapshot> children = dataSnapshot.getChildren();
            final ArrayList<Deals_Information> myArray = new ArrayList<>();

            for (DataSnapshot child : children) {
                Deals_Information deals_information = child.getValue(Deals_Information.class);
                myArray.add(deals_information);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
DMQ95
  • 1,201
  • 3
  • 9
  • 8
  • java.lang.Random is your friend....as one could have probably found out by typing java + random into google. – OH GOD SPIDERS Feb 21 '17 at 17:52
  • Possible duplicate of [Retrieving a random item from ArrayList](http://stackoverflow.com/questions/5034370/retrieving-a-random-item-from-arraylist) – moondaisy Feb 21 '17 at 17:52
  • Possible duplicate of [Randomly select an item from a list](http://stackoverflow.com/questions/12487592/randomly-select-an-item-from-a-list) – Todd Sewell Feb 21 '17 at 17:53
  • @moondaisy That's a bad one to link in my opinion because the actual answer is hidden in a comment to the accepted answer. – Todd Sewell Feb 21 '17 at 17:53

2 Answers2

1

Use Random to get a random int from the range of 0 and the size-1 of your collection.

Since Java 1.7, the recommended Random implementation is ThreadLocalRandom.

private int randomInt(final int from, final int to) {
    return ThreadLocalRandom.current().nextInt(from, to);
}
Dreando
  • 579
  • 1
  • 4
  • 10
0

Because ArrayLists have a get() function, the way to do this is to first generate a random number by using the math.random() function, and then use the get() function of your ArrayList to call the object at that randomly generated index.

Lavaman65
  • 863
  • 1
  • 12
  • 22