in process …


Something bad happened. You should try to fix …


The action is completed.

Hot Springs

Hot tags


When you define a generic class, you can



Begin by examining a non-generic class that operates on objects of any type. It needs only to provide two methods: which adds an object to the box, and , which retrieves it:

This defines the type aliases and which correspond to the return types from and . These types (and the corresponding functions) are generic in and can be made specific by writing , , , or .Redundant arguments are skipped, e.g.:

In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a class with an empty set of type arguments () as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, , is informally called . For example, you can create an instance of with the following statement:

In fact, the compiler replaces all reference to parameterized type E with Object, performs the type check, and insert the required downcast operators. For example, the is compiled as follows is compatible with codes without generics):Clearly, can be interpreted as , which is applicable to all Java classes.

The other thing all Java developers know is that you can’t add primitive types to generic collections. That means you can’t define or . Fortunately, the same version of Java that introduced generics also added autoboxing and unboxing to the language. As a result, when you want to store primitives in a generic type, you declare the type using the wrapper class. See .

Related links


type java arguments generic types