Talking about the difference between int and Integer


Preface

Understanding the basic data types will help us make better use of the syntactic sugar provided by java in programming and achieve more efficient code.


One, int and Integer definition

Most of us are familiar with the concept of integers from our elementary school days. It is a value with no decimal part.
In other words, integers are similar to sets of integers, but negative numbers are also added. Therefore, it is both positive and negative non-decimal numbers.
When we talk about integers in computer programming languages ​​such as Java, we are talking about similar things. It is a memory location, or position, which has a non-decimal or non-decimal or number, whether it is positive or negative.
Integer is a wrapper class corresponding to int. It has an int type field to store data and provides basic operations such as mathematical operations, conversion between int and string, etc. In Java 5, automatic boxing and automatic unboxing functions (boxing/unboxing) have been introduced. Java can automatically convert based on the context, which greatly simplifies related programming.

Two, expansion

Java's 8 primitive data types (Primitive Types, boolean, byte, short, char, int, float, double, long). Although the Java language claims that everything is an object, primitive data types are the exception.
Integer is a wrapper class corresponding to int. It has an int type field to store data and provides basic operations such as mathematical operations, conversion between int and string, etc. In Java 5, automatic boxing and automatic unboxing functions (boxing/unboxing) have been introduced. Java can automatically convert based on the context, which greatly simplifies related programming.

Regarding the value cache of Integer, this involves another improvement in Java 5. The traditional way of constructing an Integer object is to directly call the constructor and directly new an object. But according to practice, we found that most of the data operations are concentrated in a limited and smaller range of values. Therefore, a static factory method valueOf has been added to Java 5, which will use a caching mechanism when calling it. Significant performance improvement. According to the Javadoc, the default cache for this value is between -128 and 127.

The caching mechanism is not unique to Integer, it also exists in some other packaging classes, such as:

Boolean, the true/false corresponding instances are cached, to be precise, only two constant instances Boolean.TRUE/FALSE will be returned.

Short, which also caches values ​​between -128 and 127.

Byte, the value is limited, so all are cached.

Character, the cache range is'\u0000' to'\u007F'.

to sum up

1 Unpacking and sealing should be used with caution in the case of big data

Guess you like

Origin blog.csdn.net/aa327056812/article/details/109520103