当前位置:网站首页>Why is it best to use equals for integer comparisons

Why is it best to use equals for integer comparisons

2022-06-26 00:41:00 White as dust


Why? Integer It is suggested to use equals Well ? It's rare “==” Is it not fragrant

1. int And int Comparison

int As 8 One of the basic types , Values are allocated on the stack . And the basic type does not provide equals The way , Only use “==”.

2. Integer And int Comparison

Integer Objects are allocated in the heap , When comparing, you need to use equals Do you ? It doesn't need to ,“==” It still smells good .
because “Integer ==int” Is equivalent to Integer.intValue() ==int Of .

	public static void main(String[] args) {
    
		System.out.println("5==5: " + test(5,5));
		System.out.println("127==127: " + test(127,127));
		System.out.println("128==128: " + test(128,128));
	}

	static boolean test(Integer num1, int num2){
    
		return num1 == num2;
	}

 Insert picture description here

3. Integer And Integer Comparison

	static boolean test(Integer num1, Integer num2){
    
		return num1 == num2;
	}

 Insert picture description here
You can see 5 and 127 Comparison ,“==” It still smells good . actual -128 To 127 stay Integer.IntegerCache There is a cache in the array of , So all in this range Integer The objects of are all the same , That is, the reference address is the same .

4. Conclusion

Integer And Integer It is better to use equals, After all, I don't know when ,Integer The value of is not in that range .
Is it possible to use int no need Integer Well ? No way ,int Default initialization value bit 0,Integer by null.

原网站

版权声明
本文为[White as dust]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206252052402716.html