language-icon Old Web
English
Sign In

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 was not fully achieved, since it was shown in 2016 that it is not guaranteed in all cases. 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 was not fully achieved, since it was shown in 2016 that it is not guaranteed in all cases. 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 not generally possible to cast an arbitrary string to an integer. 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.

[ "Java annotation", "strictfp", "Java concurrency" ]
Parent Topic
Child Topic
    No Parent Topic