¡GoConqr estrena diseño! Cuéntanos qué te parece.

Apuntes

Java Generics with Examples

Reyou App k o Inglés 1 página

Contenido del apunte (1)

Página 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");

Información

Descripción
o k Apunte sobre Java Generics with Examples, creado por Reyou App el 30/06/2023.
Creado por
Reyou App · jun 2023
Actualizado
30 jun 2023
Visitas
0
Valoración

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué te parece el nuevo diseño?

¿Te gusta?