Javatpoint Logo
Javatpoint Logo

Generic Programming in Java Example

Generics are a facility of generic programming that were added to the Java programming language in 2004. With the help of generic programming developers can create programs that can handle many data types. It is an effective strategy that enhances the readability, maintainability, and reusability of code. Generics, a concept that was introduced in Java 5, is how generic programming is accomplished in Java. We will go over the idea of generic programming in Java, its advantages, and give an example of how to implement it in this post.

What is Generic Programming?

Programmers can use the approach of generic programming to create code that is not unique to any one data type. The code can instead be designed to deal with a variety of data types. Generics are used in Java to do this. Classes and methods are more adaptable and reusable when they may be parameterized with one or more data types thanks to generics.

Benefits of Generic Programming in Java

Code Reusability: Generic programming enables code to be written once and used for a variety of data types, cutting down on the amount of code that needs to be produced. The code is now easier to maintain and more reusable.

Type Safety: Generics offer compile-time type safety, which helps to catch problems at the time of coding rather than after they have been executed. By doing this, the code becomes more robust and the possibility of production errors is decreased.

Improved Readability: Generics improve readability by making it explicit which data types a class or method is meant to operate on. Developers will have an easier time understanding the code as a result, which lowers the risk of mistakes.

Example of Generic Programming in Java

Let's take a look at an example of how to implement generic programming in Java. In this example, we will create a generic class called Box that can hold any type of object.

In this illustration, the type T, which can be any data type, is used to parameterize the Box class. An object of type T may be set and retrieved from the Box using the two methods getObject and setObject provided by the class.

We only need to make an instance of the Box class and specify the desired data type in order to use it:

An instance of the Box class using the Integer data type has been constructed in this example. By utilising the getObject method, we were able to retrieve the Box's value, which was set to 10. Finally, the value has been printed to the console.

Example 1: A Generic Class for Adding Two Numbers

In this example, we will create a generic class called AddNumbers that can add two numbers of any data type. We will then create instances of the class and use them to add two integers and two doubles.

AddNumbers.java

Output:

Integer Result: 5
Double Result: 6.0

In this example, we have created a generic class called AddNumbers that takes two parameters of any data type that extends the Number class. The add() method checks the type of the parameters and returns their sum. In the main method, we have created instances of the class with integer and double parameters, and we have printed the results of the addition.

Example 2: A Generic Method for Finding the Maximum Value

In this example, we will create a generic method called findMax that can find the maximum value in an array of any data type that implements the Comparable interface. We will then create an array of integers and an array of strings, and use the method to find the maximum value in each array.

FindMax.java

Output:

Max Integer: 5
Max String: elephant

In this example, we have created a generic method called findMax that takes an array of any data type that implements the Comparable interface. The method sorts the array and returns the maximum value. In the main method, we have created an array of integers and an array of strings, and we have used the findMax method to find the maximum value in each array.

Example 3: A Generic Method for Printing Arrays

In this example, we will create a generic method called printArray that can print any type of array. We will then create an array of integers and an array of strings, and use the method to print each array.

PrintArray.java

Output:

Integer Array: 1 2 3 4 5 
String Array: cat dog elephant bird 

In this example, we have created a generic method called printArray that takes an array of any type and prints each element in the array. In the main method, we have created an array of integers and an array of strings, and we have used the printArray method to print each array.

Example 4: A Generic Class for a Pair of Objects

In this example, we will create a generic class called Pair that represents a pair of objects. We will then create instances of the class with different data types, and use them to print the values of the objects in each pair.

Pair.java

Output:

First Value: 10
Second Value: hello
First Value: 3.14
Second Value: a

In this example, we have created a generic class called Pair that takes two parameters of any type. The class has methods to get the values of the first and second objects in the pair. In the main method, we have created instances of the class with integer and string, and double and character data types, and we have printed the values of the objects in each pair.

Example 5: A Generic Interface for Sorting Objects

In this example, we will create a generic interface called Sortable that represents a sortable object. We will then create a class called Person that implements the Sortable interface, and use it to sort an array of person objects based on their age.

Person.java

Output:

Before Sorting: [Name: John, Age: 20, Name: Mary, Age: 25, Name: David, Age: 18, Name: Sarah, Age: 22]
After Sorting: [Name: David, Age: 18, Name: John, Age: 20, Name: Sarah, Age: 22, Name: Mary, Age: 25]

In this example, we have created a generic interface called Sortable that has a single method called compare. We have then created a class called Person that implements the Sortable interface, and defines the compare method to compare two person objects based on their age.

In the main() method, we have created an array of person objects, and printed the array before sorting. We then use the Arrays.sort() method to sort the array using a lambda expression that calls the compare method on each pair of person objects. Finally, we print the sorted array.

In the above example, we have demonstrated how generic programming can be used to sort objects of a custom class based on a specific field, in this case, the age field of the Person class.

Conclusion

Developers can construct code that is not unique to any one data type using the potent method of generic programming. It enhances the readability, maintainability, and reusability of code. Generics in Java offer a mechanism to perform generic programming by allowing classes and functions to take one or more data types as parameters. Generics allow programmers to produce more adaptable, reusable code that is simpler to maintain and less prone to errors.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA