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) {

        }
    });
}
4
  • java.lang.Random is your friend....as one could have probably found out by typing java + random into google. Commented Feb 21, 2017 at 17:52
  • Possible duplicate of Retrieving a random item from ArrayList Commented Feb 21, 2017 at 17:52
  • Possible duplicate of Randomly select an item from a list Commented Feb 21, 2017 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. Commented Feb 21, 2017 at 17:53

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.