Learn How to work with Java Generics

0
1826
java-generics

java-generics

The newest version of Java 8 SE has taken the world by storm. It boasts of its new programming capabilities and features. Overall, it claims that it actually could decrease the work of its users and enhance the quality of coding greatly. However, in order to understand its features, one must first know about generics. Often, a situation arises in Java which requires you to check what values you are actually adding to your ArrayList and Collections and also want specific objects in your ArrayList. You may then use the Generics function of Java. Generics also allow the user to check whether the Comparator used for sorting the objects is compatible or not. This function is a compile type function, so it only runs while compiling the code, akin to C++ templates.

In this article, we will know more about the importance of generics and will learn how to handle them.

Why generics are important?
Generics are very important in the sense that they allow the types of objects to define the class of objects. Thus, generics can be used to re-use codes without any risk of exceptions. Generic code has a lot of benefits over non-generic ones. They help in faster coding and after deployment there is a lesser chance of bugs and exceptions occurring in the Java application. Some of the benefits of using generics in Java are given below.

  • Better type-checking while the code is being deployed: If an exception occurs in a non-generic code, it can be very hard to resolve as it may be a runtime-error. Runtime errors are very hard to locate and resolve. On the other hand, if a generic code is compiled, it is more likely to have compile-time type checking errors as the Java compiler strictly checks generic codes for type errors. Compile-time errors are much easier to resolve compared to runtime errors. It also saves time by negating errors like ClassCastException which are runtime errors.
  • No casting is required: Casting is a requirement in non-generic code which allows the Java compiler to know about the objects and their types in an ArrayList or a collection. Incorrect definition can send errors like ClassCastException which are runtime errors. These errors can be very hard to resolve as the developer will have to sift through the whole code in order to search for the erratic casting part. On the other hand, generics completely negate this threat as it doesn’t require casting at all. The type of the object is already known by the compiler, so the code doesn’t require separate casting. This not only stops most of the runtime errors, but also saves time which would otherwise be wasted while writing useless casting codes.
  • Generic algorithms can be created: Generics in Java allow the developers to implement an interesting type of algorithm known as a generic algorithm. Generic algorithms allow the developers to quickly create collections of different types, while reusing code. This allows faster coding which is accurate and also type-safe. Also, the generic algorithm can be changed according to the type and the requirements of the application and the developer.
  • Generics can be used for the development of special Java containers. Suppose you want to create a container which can be used to transport objects in an application. Sounds simple enough? But there is a catch. There are many different kinds of objects, and each one has a completely different type and use. So the container you created must accommodate all kinds of objects. There are many possible solutions for this. You can create a container which will keep the type of the object and cast it. However, this container can be very risky to use, as it can produce different exceptions while running due to its type-unsafe nature. Generics can be used here, in order to remove this limitation by changing the type to generic type. This will make the container type-safe and will remove any chances for exceptions. Such usage is common in generics.

Exploring – How generics work?
Java has some collection classes, for example ArrayList, HashMap and TreeList. These classes contain objects of the same type, also called generic objects. Earlier, before the implementation of generics, any kind of object could have been kept in a class and the compiler would not warn about the type of the objects. However, Java 1.5 introduced casting, which means that the type of objects had to be defined in order to prevent loopholes in the Virtual Machine, which were susceptible to exploitation maliciously.
Generics were truly implemented in JDK 5. It means that a generic class contains objects of only one type. This meant that casting was no longer required and the whole code was written according to a specific type which is explained to the compiler while compiling the program. In this way, generics work in Java 5 and beyond.

Environment setup:
To configure the environment follow the steps below:

Now your environment is ready to write generic classes in Java. In the next section, we will create a sample application.

Sample application:
In this example, we will write a generic class which will take an integer and string input. And then it will print the output.

Listing 1: Generic class example

package com.eduonix;
public class GenericClassDemo<G> {
   private G g;
   public void addVal(G g) {
      this.g = g;
   }
   public G getVal() {
      return g;
   }
   public static void main(String[] args) {
     //Creating integer and string type
      GenericClassDemo<Integer> intGen = new GenericClassDemo<Integer>();
      GenericClassDemo<String> stringGen = new GenericClassDemo<String>();
    
      //Adding integer and string values
      intGen.addVal(new Integer(555));
      stringGen.addVal(new String("Welcome to Eduonix"));

     //Printing integer and string values
System.out.println("Let's check the integer value :%d\n\n", intGen.getVal());
System.out.println("Let's check the string Value :%s\n", stringGen.getVal());
   }
}

The output will be as shown in the screen shot below.

generic-class-example

Image1: Output

Conclusion:
Generic is a very important part of Java. Today, many features which are a staple in Java are usable because of this single mechanism. It allows faster and more efficient coding and also negates loopholes and security issues. While this article talks about the fundamental areas of generics, generics can be understood in a better way if the developer actually practises coding.

LEAVE A REPLY

Please enter your comment!
Please enter your name here