I had dinner with a friend yesterday. He said whether two integer values are equal. Here, the manager also explained the problem of Java integer value comparison. This is a frequent problem during the interview.
First, let's look at an example:
1 Public Class Test {
2
3 /***/ /**
4* Integer size comparison
5*@ AuthorManager
6*/
7 Public Static Void Main (string [] ARGs) {
8Integer= 10;
9Integer B= 10;
10System. Out. println ("A = B:" +String. valueof (=B ));
11System. Out. println ("A. Equals (B ):" +String. valueof (A. Equals (B )));
12}
13 }
14
Run the command. The result on the console is as follows:
A = B: True
A. Equals (B ): True
When we change the value
1 Public Class Test {
2
3 /***/ /**
4* Integer size comparison
5*@ AuthorManager
6*/
7 Public Static Void Main (string [] ARGs) {
8Integer= 1000;
9Integer B= 1000;
10System. Out. println ("A = B:" +String. valueof (=B ));
11System. Out. println ("A. Equals (B ):" +String. valueof (A. Equals (B )));
12}
13 }
Run the command again.
A = B: False
A. Equals (B ): True
Why? I was a little confused. If you are a little impulsive, you can directly open the source code.
In fact, when we use integer a = number; to assign values, the integer class calls the public static integer valueof (int I) method.
1 Public Static Integer valueof ( Int I) {< br> 2 If (I >= - 128 & I <= integercache. high)
3 return integercache. cache [I + 128 ];
4 else
5 return New INTEGER (I );
6 }
Let's take a look at the valueof (int I)CodeIt can be found that it makes an if judgment on the input parameter I. In the case of-128 <= I <= 127, the int original data type is used directly, and an object is new when the range is exceeded. We know that the "=" symbol is the memory address of the comparison object, while the original data type is the direct comparison data value. Then this problem is solved.
Why is the value in the range of-128 <= I <= 127 when int type is used? We know that the eight-bit binary representation ranges from-128 to 127. This is probably the reason.
Record the problems that occur at ordinary times so that you can make progress at 1.1 points.