GoConqr hat ein neues Design! Sag uns, wie es dir gefällt.

Notizen

Java Generics with Examples

Reyou App k o Englisch 1 Seite

Inhalt der Notizen (1)

Seite 1

As we know that, Generics was added in Java 5 to provide compile-time type checking and removing the risk of ClassCastException that was common while working with collection classes.

The whole collection framework was re-written to use generics for type-safety. Let’s see in this post how generics help us using collection classes safely.

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

Benefits of Generics

1. Stronger type checks at compile time

A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

Example: In this example, List holds only a String type of objects in generics. It doesn’t allow to store other objects

List<String> list = new ArrayList<String>(); list.add("abc");

Informationen

Beschreibung
o k Notiz am Java Generics with Examples, erstellt von Reyou App am 30/06/2023.
Erstellt von
Reyou App · Jun 2023
Aktualisiert
30 Jun 2023
Aufrufe
0
Bewertung

Feedback

Worum geht es?

Wie gefällt dir das neue Design?

Dein Eindruck