Collections and Generics
Java collections
Homogeneous list
A homogeneous list is where the elements are restricted to a specific type such as a list of Person objects, a list of String objects, a list of Book objects, and so forth. Specifying the element type improves the program reliability because an error such as trying to add a wrong type of object to alist can be caught during the compile time.
To specify a homogeneous list, we must include the type elements in the declaration and creation statements.
List<Person> friends; ... friends = new ArrayList<Person>();
The general syntax for the declaration is
interface-or-class-name <element-type> identifier;
And the general syntax for the creation is
identifier = new class-name <element-type> (parameters);
We can combine the two into a single statement as
interface-or-class-name <element-type> identifier = new class-name <element-type> (parameters);
List<Person> friends = new ArrayList<Person>();
Person person;
person = new Person("Jane", 10, 'F');
friends.add(person);
person = new Person("Jack", 16, 'M');
friends.add(person);
person = new Person("Jill", 8, 'F');
friends.add(person);
person = new Person("John", 12, 'M');
friends.add(person);
Create a homogeneous ArrayList that contains only Book objects
import java.util.*;
ArrayList<Book> bookList = new ArrayList<Book>();
bookList.add(new Book("Jane Austin"));
bookList.add(new Book("Charles Dickens"));
bookList.add(new Book("henry James"));
The following would result in a compile time error:
bookList.add(new String("Java"));
Here is how we access the elements of bookList via an iterator:
Iterator<Book> itr = bookList.iterator();
while (itr.hasNext()) {
Book book = itr.next(); // typecast is not required
System.out.println(book.getAuthor());
or
for (Book book = bookList) {
System.out.println(book.getAuthor());
}