A summary of the mistakes that long and integer are easy to make in Java

Today, many high-risk vulnerabilities are found after scanning the project with findbugs. A very common one is to compare two long or integer directly with = =. In fact, this is wrong.

Because long and inger are both wrapper types and objects. Instead of the ordinary types of long and int, they must all use equals when comparing, or it is also possible to use the longvalue() or intvalue() method to get the value of their basic type, and then use = = for comparison.

However, there is a special case. In fact, long and integer cache -128 ~ 127 objects. You can see that there is a longcache class in the long type source code. The code is as follows:

Let's take a look at this example:

The printed result is:

reason

First, let's look at long a = 5L; How it wraps a basic type long into an object long.

You can write a test class and decompile it to see how Java parses such a command as long a = 5L.

The test classes are as follows:

Then use javap - verbose test06 to see the decompilation results. The following is the output:

From 8 in the code, we can see that a class method of long is called Valueof (long), so it can be concluded that long a = 5L is actually equal to long a = long valueOf(5) ;

Then look at long How is the valueof () method defined

At a glance, the basic type value will be judged first. If it is between - 128 and 127, the cached object will be taken directly from longcache and returned. Otherwise, a new long object will be returned.

Now it is not difficult to understand the results obtained from the execution of test05 program. Because a and B are equal to 5 and within - 127 ~ 128, they are all long objects returned directly from longcache, so when they use = = comparison, It is equal (for object types, = = refers to the reference of two objects pointing to the address in the heap), while C and D are equal to 129, not between - 127 ~ 128, so they are two new long objects created by new respectively. Using = = to compare is naturally unequal.

Long overrides the equals method:

It passed first The longvalue () method obtains the value of the basic type long of the long object and then compares it.

Therefore, for the comparison between integer and long, it is best to use equals to ensure the desired results.

Integer is the same as long. There are no examples here.

The above detailed summary of the mistakes that long and integer are easy to make in Java is all that Xiaobian has shared with you. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>