ArticleslgStudy

biology

Generics in Java

Generics in Java is a biology topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Generics in Java rather than just read about it. In short: 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".

Key takeaways

  • Generics in Java belongs to biology; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Generics in Java to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Generics in Java from memory before moving on to harder problems.

Reference excerpt

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.

Hierarchy and classification According to Java Language Specification:

A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations. These are often a single capital letter, but those longer than one letter are typically written in ALL_CAPS (unlike other languages like C++, C#, and Rust where they are PascalCase), for instance java.util.PrimitiveIterator<T, T_CONS>. A class is generic if it declares one or more type variables. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime. An interface is generic if it declares one or more type variables. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime. A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface. A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface.

Motivation 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 java.lang.String to the java.util.ArrayList. Finally, it attempts to retrieve the added java.lang.String and cast it to an java.lang.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, and its collection-like data structures typically store data 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:

The type parameter java.lang.String within the angle brackets declares the java.util.ArrayList to be constituted of java.lang.String (a descendant of the java.util.ArrayList's generic java.lang.Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as java.lang.String by the code generated by the compiler. The logical flaw in the third line of this fragment will be detected as a compile-time error (with J2SE 5.0 or later) because the compiler will detect that v.get(0) returns java.lang.String instead of java.lang.Integer. For a more elaborate example, see reference. Here is a small excerpt from the definition of the interfaces java.util.List and java.util.Iterator in package java.util:

Generic class definitions Here is an example of a generic Java class, which can be used to represent individual entries (key to value mappings) in a map:

This generic class could be used in the following ways, for example:

It outputs:

grade: (Mike, A) mark: (Mike, 100) 13 is prime.

Generic method definitions Here is an example of a generic method using the generic class above, for a generic type T:

In many cases, the user of the method need not indicate the type parameters, as they can be inferred:

The parameters can be explicitly added if needed:

The use of primitive types is not allowed, and boxed versions must be used instead; only reference types may be stored in a generic type parameter. For instance, Entry<int, int> pair; fails compiling, and should instead be using the wrapper classes for primitives (like Entry<Integer, Integer> pair;. There is also the possibility to create generic methods based on given parameters.

In such cases one cannot use primitive types either, e.g.:

While primitives cannot be stored, arrays of primitives (as they are objects, not primitives themselves) can:

Diamond operator Using type inference, Java SE 7 and above allow the programmer to substitute an empty pair of angle brackets (<>, called the "diamond operator") for a pair of angle brackets containing the one or more type parameters that a sufficiently close context implies. While <> is often called the "diamond operator", it is not an operator, just an empty type parameter list. Thus, the above code example using Entry can be rewritten as:

The so-called diamond operator does not exist in other Java-derived languages like C# or Kotlin, which have their own ways to avoid redundant type information. While something visually similar exists in C++, it does not denote type parameter deduction, but rather refers to only the default type parameter.

Type wildcards

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Generics in Java

Start with the simplest possible case. Write down what Generics in Java claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In biology, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Generics in Java before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Generics in Java ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Generics in Java

In research
Generics in Java appears in biology research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Generics in Java in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Generics in Java is common in secondary-school and first-year university syllabi. It links to neighbouring topics Java (programming language), Polymorphism (computer science), so understanding it makes those chapters shorter.
In everyday life
Look for Generics in Java outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Generics in Java in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Generics in Java means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Generics in Java out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Generics in Java in simple terms?

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".

Why does Generics in Java matter?

Because it connects several biology ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Generics in Java?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Generics in Java.

Tags

  • Java (programming language)
  • Polymorphism (computer science)

Keep exploring