Java Reference
In-Depth Information
7-5. Safely Enabling Types or Methods to
Operate on Objects of Various Types
Problem
Your application makes use of many different object types, and there are containers
within your class that are available for holding each of these different types. You are
interested in ensuring your application remains bug-free, yet you would like to dynam-
ically change the type of object a particular container may hold.
Solution
Make use of generic types to decouple the type from the container. Generics are a way
to abstract over object types, not explicitly declaring what the type of an object or con-
tainer should be. You'll likely first encounter generic types when using the interfaces
and classes that are part of the Java Collections Framework ( ht-
tp://download.oracle.com/javase/tutorial/collections/ ) . The
Collections Framework makes heavy use of Java generics. All collection types are
parameterized to allow you to specify, at the time of instantiation, the type of elements
the collection can hold. The following example code demonstrates how to use generics
in a couple of different scenarios. The comments in the code indicate where the gener-
ics are utilized.
public class MainClass {
static List<Player> team;
private static void loadTeam() {
System.out.println("Loading team...");
// Use of the diamond operator
team = new ArrayList<>();
Player player1 = new Player();
player1.setFirstName("Josh");
player1.setLastName("Juneau");
player1.setGoals(5);
Search WWH ::




Custom Search