12.02. Understanding generics in Java

Understanding generics in Java

  • Eclipse: Oxygen
  • Java: 1.8

This tutorial deals with the type parameters that are used in generics in Java. The type parameters related to generics are described here. Here its use in the program is shown. Users will be able to better use generics with this.

In the following program we write generic functions that can be called with different types of arguments depending on the type of arguments passed to the generic method, the compiler manages each method without any runtime error.

In the following program, we demonstrate that using generics converts runtime exceptions into a compile-time exception.

Here we want to apply the restriction at the time of defining List, hence we create a list with String specified. Now compiler does not allow any other data type value.

Output

In the following program, we demonstrate the entire operation through the Integer object.

Output

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments