Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use java generic container Collection

Shulou Source: shulou.com Published: 2022-05-31 11:47:57 10月14日 Update

This article mainly introduces the relevant knowledge of "how to use java generic container Collection". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use java generic container Collection" can help you solve the problem.

Let's start with a simple example:

Public void testGenerics () {

Collection numbers = new ArrayList ()

Numbers.add (1); / / ok

Numbers.add (0.1); / / ok

The range represented by Collection is larger than that of Collection

Objects2.add (1) cannot be called because the compiler cannot infer exactly what kind of data type container objects2 is, which may result in a runtime type conversion exception

The correct way to represent a collection of arbitrary data types is Collection

Collection cannot represent any type of collection.

Why doesn't Collection represent any type of collection? in fact, the compiler thinks there is a risk of type conversion errors:

Public void testGenerics () {

Collection integers = new ArrayList ()

Collection objects = integers; / / oops!

/ / don't work, which type of 'objects2' contains is uncertain

Objects.add ("1")

Integer one = objects.iterator () .next (); / / oops! Crash

}

Collection can add data to the container, because Object is the parent class of all objects, is a known type, and can be judged by obj instanceof Object.

Collection cannot put data into the container because? (UnknownType) is an unknown type and cannot determine the result of obj instanceof UnknownType

? Represents an unknown type, and Object represents a known type

If Collection means any type, according to Murphy's law (what may happen is bound to happen), then the crash in the above example is bound to happen. (another online glitch)

This is the end of the introduction to "how to use the java generic container Collection". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Types containers examples compilers compilers data objects knowledge size necessity method result industry response affirmative different no robust accurate Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Redmi vpn Xiaomi NVidia