Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Why are the object values of integer wrapper classes compared with the equals method

Shulou Source: shulou.com Published: 2022-06-02 03:09:41 09月17日 Update

This article mainly introduces "why the integer wrapper class object value is compared with the equals method". In the daily operation, I believe that many people have doubts about why the integer wrapper class object value is compared with the equals method. The editor consulted all kinds of data and sorted out a simple and easy-to-use operation method. I hope it will be helpful for everyone to answer the doubt that "Why the integer wrapper class object value is compared with the equals method". Next, please follow the editor to study!

Analysis of Integer caching problem

Take a look at the following sample code and think about the output of this code:

Public class IntegerTest {public static void main (String [] args) {Integer a = 100,b = 100c = 666d; System.out.println (a = = b); System.out.println (c = = d);}}

The answer can be obtained by running the code, and the output results of the program are: true, false.

So why is the answer this way?

Combined with the description of "Alibaba Java Development Manual", many people may answer: because the value between-128and 127is cached, there is no then.

So why is the value of this range cached? Can the cache interval be modified? Are there similar caches for other packaging types?

Next, let's analyze it together.

Source code analysis

First of all, we can analyze the problem through the source code.

We know that Integer var =? Formal declaration of variables, the Integer object is constructed through java.lang.Integer#valueOf (int).

How do you know that the valueOf () method will be called?

You can go through the break point and transfer it here after running the program.

First, take a look at the java.lang.Integer#valueOf (int) source code:

/ * Returns an {@ code Integer} instance representing the specified * {@ code int} value. If a new {@ code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@ link # Integer (int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range-128to 127, * inclusive, and may cache other values outside of this range. * * @ param i an {@ code int} value. * @ return an {@ code Integer} instance representing {@ code I}. * @ since 1.5 * / public static Integer valueOf (int I) {if (I > = IntegerCache.low & & I =-128 & & l

Tags: Cache object instruction type scope offset wrapper compilation code problem method analysis comment source code variable maximum data learning between parameters Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple NVidia Docker Shulou Tech Info Shulou Information