Home > Java > javaTutorial > body text

What is the purpose of universal collections in Java?

WBOY
Release: 2023-09-16 21:53:02
forward
884 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template