Site Search:

Create and use a generic class

<Back
Before java 5, programmers write code like the following.

List objects = new ArrayList();
objects.add("a string");
objects.add(new StringBuilder());
//100 lines later
(StringBuilder)objects.get(0);

Since any type of Objects can be added to the list, the code compiles but throws ClassCastException at run time.
After java 5, programmer can document what type of class the List can have with generics.


List<String> objects = new ArrayList<>();
objects.add("a string");
objects.(new StringBuilder());
//100 lines later
(StringBuilder)objects.get(0);         //not compile


The syntax for introducing a generic is to declare a formal type parameter in angle brackets. Given that documentation, the compiler can find the type mismatch for you at compile time and refuse to compile, thus saving your program from crashing at run time. This chapter will discuss generics in detail.
We will introduce diamond operator, followed by generic classes, interfaces and methods, finally we talk about wild cards -- namely unbounded wildcards, upper-bounded wildcards and lower-bounded wildcards.

The diamond Operator

Generic Classes, Interfaces and Methods

WildCards

The following youtube video provides in-depth background about the generics from the architects perspective. You can skip it if you only concerned about the application of generic syntax.