I do not understand the wrapper class and autoboxing?

I am reading a book called Java in Two Semesters, and I really don't understand the wrapper class and autoboxing.

Can you explain this to me with some code?

And it really bothers me:

Object [] anArray = new Object[20]; anArray[0] = new Integer (37); 

What does Object mean here, is the object a class, and the code creates an array for it?

I have a book, I have a little understanding, I just need someone who will explain this to me for a while. If I read something on the Internet, I just get confused.

+4
source share
4 answers

Wrapper Classes

Wrapper classes are used to encapsulate primitive types so that you can define them against them. For example, the ToString () method is defined in a wrapper class, but it cannot be called in a primitive type.

Autoboxing

Autoboxing allows you to automatically convert between primitive types and cover types

With auto boxing

 int i; Integer j; i = 1; j = 2; i = j; j = i; 

No Auto Boxing

 int i; Integer j; i = 1; j = new Integer(2); i = j.intValue(); j = new Integer(i) 

About the second section of the question

 Object [] anArray = new Object[20]; 

A certain array is capable of objects (in a particular case, it is 20 objects), so it allows you to hold any object in each position of the array,

 anArray[0] = new Integer (37); 

and Integer is a subclass of Object. Thus, it allows you to store Integer in an array

+6
source

Wrapper classes are used to convert primitive data types to objects, and autoboxing means implicit conversion of a primitive data type to an equivalent object of the wrapper class, for example, int will be converted to an Integer object.

Read more in the following articles:

Explain Wrapper Classes in Java

What's New in Java 5 / J2SE 5.0: Auto Update

+1
source

An object is a class, and anArray is defined as an array of 20 objects. This allows you to insert things of different types into each index of the array, rather than force each index to be the same type. In the example, index 0 is set to an integer, but index 1 can be set to a logical value, for example.

0
source

The java Wrapper class provides a mechanism for converting a primitive into an object and an object into a primitive.

Since J2SE 5.0, the autoboxing and unboxing function converts a primitive into an object and an object into a primitive automatically. The automatic conversion of a primitive to an object is known and autoboxing and vice versa is unpacked.

Autoboxing is an automatic conversion that the Java compiler does between primitive types and the corresponding wrapper classes of objects. For example, converting int to Integer, double to Double, etc. If the conversion goes the other way, it's called Unboxing.

Here is the simplest example of Autoboxing:

Character ch = 'a';

0
source

Source: https://habr.com/ru/post/1382892/


All Articles