This site requires JavaScript, please enable it in your browser!
Greenfoot back
A_User
A_User wrote ...

2023/3/7

Lists

A_User A_User

2023/3/7

#
How do you create a list l and then access a random element of that list?
danpost danpost

2023/3/7

#
A_User wrote...
How do you create a list l and then access a random element of that list?
The java.util.List class is abstract, which means you cannot directly create a List object from that class. You can create a List object via a non-abstract class that extends the List class, such as the ArrayList class):
java.util.List list = new java.util.ArrayList();
You could import the two packages:
import java.util.List;
import java.util.ArrayLIst;
to simplify the line to:
List list = new ArrayList();
Before getting a random element from the list, it should be tested for emptiness if it has any chance of being empty:
if ( ! list.isEmpty() )
So, it might look like this:
Object obj = null; // for element from list
if ( ! list.isEmpty() ) obj = list.get( Greenfoot.getRandomNumber( list.size() ) );
if ( obj != null) // etc.
You need to login to post a reply.