Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a random item from ArrayList [duplicate]

I'm learning Java and I'm having a problem with ArrayList and Random.

I have an object called catalogue which has an array list of objects created from another class called item.

I need a method in catalogue which returns all the information on one of the itemobjects in the list.
The item needs to be selected at random.

import java.util.ArrayList; import java.util.Random;  public class Catalogue {     private Random randomGenerator = new Random();     private ArrayList<Item> catalogue;      public Catalogue ()     {         catalogue = new ArrayList<Item>();       }      public Item anyItem()     {         int index = randomGenerator.nextInt(catalogue.size());         System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");         return catalogue.get(index);     } 

When I try to compile I get an error pointing at the System.out.println line saying..

'cannot find symbol variable anyItem'

like image 830
Will Avatar asked Feb 17 '11 20:02

Will


People also ask

How do you randomly get an element from an ArrayList?

nextInt() method of Random class can be used to generate a random value between 0 and the size of ArrayList. Now use this number as an index of the ArrayList. Use get () method to return a random element from the ArrayList using number generated from nextInt() method.

Does ArrayList have random access?

Search Operation This is because ArrayList allows random access to the elements in the list as it operates on an index-based data structure while LinkedList does not allow random access as it does not have indexes to access elements directly, it has to traverse the list to retrieve or access an element from the list.

Is ArrayList clone a deep copy?

ArrayList clone() method is used to create a shallow copy of the list.


1 Answers

anyItem is a method and the System.out.println call is after your return statement so that won't compile anyway since it is unreachable.

Might want to re-write it like:

import java.util.ArrayList; import java.util.Random;  public class Catalogue {     private Random randomGenerator;     private ArrayList<Item> catalogue;      public Catalogue()     {          catalogue = new ArrayList<Item>();         randomGenerator = new Random();     }      public Item anyItem()     {         int index = randomGenerator.nextInt(catalogue.size());         Item item = catalogue.get(index);         System.out.println("Managers choice this week" + item + "our recommendation to you");         return item;     } } 
like image 108
Robby Pond Avatar answered Sep 18 '22 17:09

Robby Pond