What are the uses of generic collections in Java?

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 29-Aug-2019 15:35:06
Advertisements