Hubbry Logo
search
logo

Generics in Java

logo
Community Hub0 Subscribers
Write something...
Be the first to start a discussion here.
Be the first to start a discussion here.
See all
Generics in Java

Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". The aspect compile-time type safety required that parametrically polymorphic functions are not implemented in the Java virtual machine, since type safety is impossible in this case.

The Java collections framework supports generics to specify the type of objects stored in a collection instance.

In 1998, Gilad Bracha, Martin Odersky, David Stoutamire and Philip Wadler created Generic Java, an extension to the Java language to support generic types. Generic Java was incorporated in Java with the addition of wildcards.

According to Java Language Specification:

The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer—an error in logic, as it is impossible to cast any string instance to an integer.

This is similar to C, which lacks generics. Collections typically store as void* (a void pointer), from which objects must be cast explicitly.

Although the code is compiled without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of logic error can be detected during compile time by using generics and is the primary motivation for using them. It defines one or more type variables that act as parameters.

The above code fragment can be rewritten using generics as follows:

See all
User Avatar
No comments yet.