Java Reference
In-Depth Information
Class Definition with a Type Parameter
You can define classes with a parameter for a type. Such a class is called a generic class
or a parameterized class . The type parameter is included in angular brackets after the
class name in the class definition heading. You may use any nonkeyword identifier for the
type parameter, but by convention, the type parameter starts with an uppercase letter.
The type parameter may be used like any other type in the definition of the class. (There
are some restrictions on where the type parameter can be used. These are discussed
later in the Pitfall section entitled “A Type Parameter Cannot Be Used Everywhere a Type
Name Can Be Used.”) For an example, see Display 14.4.
A generic class is used like any other class, except that you specify a reference type,
typically a class type, to be plugged in for the type parameter. This class type (or other
reference type) is given in angular brackets after the name of the generic class, as shown in
the following example:
EXAMPLE
Sample<String> object1 = new Sample<String>();
object1.setData("Hello");
Sample<String> is said to instantiate the generic class Sample .
Type Inference in Java 7
Starting with version 7, Java supports a feature called type inference . In type inference,
Java is able to infer the base type in the call to the constructor based on the base type used
in the variable declaration. That is, the following
ClassName <Base_Type> Object_Name = new ClassName <Base_Type >();
can equivalently be written in Java 7 as:
ClassName< Base_Type> Object_Name = new ClassName<>();
The new format saves a little bit of typing and is also somewhat cleaner to read. However,
programmers have been using the earlier format for many years, so you are likely to see it
in existing code. For greater compatibility, the examples in this topic do not use the new
syntax supported in JDK 7.
EXAMPLES
ArrayList<String> list = new ArrayList<>();
ArrayList<Double> list2 = new ArrayList<>(30);
 
Search WWH ::




Custom Search