Java Reference
In-Depth Information
This line does two things:
It retrieves the response at position index using the get method.
It returns the selected string as a method result, using the return statement.
If you are not careful, your code may generate a random number that is outside the valid indices
of the ArrayList . When you then try to use it as an index to access a list element, you will get
an IndexOutOfBoundsException .
5.4.4
Reading documentation for parameterized classes
So far, we have asked you to look at the documentation for the String class from the java.
lang package and the Random class from the java.util package. You might have noticed
when doing this that some class names in the documentation list look slightly different, such as
ArrayList<E> or HashMap<K, V> . That is, the class name is followed by some extra infor-
mation in angle brackets. Classes that look like this are called parameterized classes or generic
classes . The information in the brackets tells us that when we use these classes, we must supply
one or more type names in angle brackets to complete the definition. We have already seen this
idea in practice in Chapter 4, where we used ArrayList by parameterizing it with type names
such as String . They can also be parameterized with any other type:
private ArrayList<String> notes;
private ArrayList<Student> students;
Because we can parameterize an ArrayList with any other class type that we choose, this is
reflected in the API documentation. So if you look at the list of methods for ArrayList<E> ,
you will see methods such as:
boolean add(E o)
E get(int index)
This tells us that the type of objects we can add to an ArrayList depends on the type used to
parameterize it, and the type of the objects returned from its get method depends on this type
in the same way. In effect, if we create an ArrayList<String> object and then the documen-
tation tells us that the object has the following two methods:
boolean add(String o)
String get(int index)
whereas if we create an ArrayList<Student> object, then it will have these two methods:
boolean add(Student o)
Student get(int index)
We will ask you to look at the documentation for further parameterized types in later sections
in this chapter.
5.5
Packages and import
There are still two lines at the top of the source file that we need to discuss:
import java.util.ArrayList;
import java.util.Random;
 
 
Search WWH ::




Custom Search