Home  >  Article  >  Java  >  What is the purpose of universal collections in Java?

What is the purpose of universal collections in Java?

WBOY
WBOYforward
2023-09-16 21:53:02878browse

What is the purpose of universal collections in Java?

Generic collections were introduced in Java 5 version. Universal collection Disable type conversion, no type conversion is required when used in a universal collection. Generic collections are type-safe and checked at compile time . These generic collections allow data types to be passed as parameters to classes. The compiler is responsible for checking the compatibility of types.

Syntax

class<type>, interface<type>

Type safety

Generics allow a single type of object.

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

Type conversion

No type conversion is required when using generics.

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

Compile time

In generics, errors are checked at Compile time.

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

The above is the detailed content of What is the purpose of universal collections in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete