Steps to work with Java generics?

Java Generics

Introduction to Java Generics

Overview:

The newest version of Java 8 SE has held 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 about its features, one must first know about generics. Saepe, 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 lot 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 allows 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, each having 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 usages are common of generics.

Must read – Interesting articles on Java

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 objects 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 the 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 following are the steps to be followed

  • Download JDK from the following link and set the class path

http://www.oracle.com/technetwork/java/javase/downloads/index.html

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

Sample application:

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

Listing 1: Generic class example

[Codicem]

package com.eduonix;

public class GenericClassDemo<G> {

private G g;

public void addVal(G g) {

this.g = g;

}

public G getVal() {

return g;

}

static vacuum publicum principale(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());

}

}

[/Codicem]

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

Java Generics

Java Generics

Image 1: Output

Conclusio:

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 much better way if the developer actually practices coding.







============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share