Comparison of the difference between collections and arrays

The difference between collection and array:

Common point: they are all containers for storing data;

Difference: the capacity of the array is fixed, and the capacity of the collection is variable;

Note: If the length of the stored data changes frequently, it is recommended to use a collection.

Container concept: Simple understanding is the box.

 

Note: Arrays can store basic data types and reference data types

          The collection can only register the reference data type. If you want the basic data type, you need the corresponding packaging class.

Reason analysis: Java collections cannot store basic data types, only references to objects.

Each collection element is a reference variable, and the actual content is stored in the heap or method area.

But the basic data types allocate space on the stack memory, and the data on the stack will be recovered at any time.

How to solve?

You can convert basic data types into object types through packaging classes and store references.

More convenient, thanks to the automatic unboxing and packing functions, the basic data types and their corresponding objects

The conversion between the two becomes very convenient, the basic data types can be automatically stored in the collection, the system

Will automatically box it into a package class, and then add it to the collection.

Basic data type Packaging
byte Byte
short Short
boolean Boolean
char Charset
int Integer
long Long
float Float
double Double

 

 

E.g:

 

Guess you like

Origin blog.csdn.net/qq_35207086/article/details/114693078