What are the uses of generic collections in Java?


The generic collections are introduced in Java 5 Version. The generic collections disable the type-casting and there is no use of type-casting when it is used in generics. The generic collections are type-safe and checked at compile-time. These generic collections allow the datatypes to pass as parameters to classes. The Compiler is responsible for checking the compatibility of the types.

Syntax

class<type>, interface<type>

Type safety

Generics allows a single type of object.

List list = new ArrayList(); // before generics
list.add(10);
list.add("100");
List<Integer> list1 = new ArrayList<Integer>(); // adding generics
list1.add(10);
list1.add("100"); // compile-time error.

Type Casting

No need for type-casting while using generics.

List<String> list = new ArrayList<String>();
list.add("Adithya");
String str = list.get(0); // no need of type-casting

Compile-time

The errors are checked at compile-time in generics.

List list = new ArrayList(); // before generics
list.add(10);
list.add("100");
List<Integer> list1 = new ArrayList<Integer>(); // adding generics
list1.add(10);
list1.add("100");// compile-time error

Updated on: 03-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements