Type parameters

  • Eclipse: Oxygen
  • Java: 1.8

As developers, we always strive to create reusable and flexible applications with different types of data. Therefore, by using generics, we can do that. But here there are also several types of parameters available, such as the element, the key value, the number, etc.

In the following example, Class Data has multiple type parameters. Data is provided using a parameterized constructor, and to retrieve the data we use the getter method.  By using multiple type’s generics, different types of data can be provided. Class Data is receiving data as a Key value pair where a key is integer and value is String.

Output

Key: 1 value: Chaand

Note: It is not compulsory that only generic class can hold a generic method

In the following example, method types of generics is created.

Display method is created with parameter at type Element and Number and value can be provided as arguments.

Output:

Key: 1 value: Chaand

Element: 2.0 Number: 25

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu