Integer的“==”

                Map<String,Integer> a=new HashMap(),b=new HashMap();
		a.put("a", 100);
		b.put("a", 100);
		a.put("c", 130);
		b.put("c", 130);
		System.out.println(a.get("a")==b.get("a"));//false
		System.out.println(a.get("c")==b.get("c"));//true
		System.out.println((Integer)130==130);//true
		System.out.println((Integer)100==100);

  在放入map的时候,自动将int 130转成了Integer,取出来的时候也是Integer,而Integer的==是判断引用等价性,

当如果整型字面量的值在-128到127之间,那么不会new新的Integer对象,而是直接引用常量池中的Integer对象

所以System.out.println(a.get("c")==b.get("c"));//true

而大于130,new 了新的Integer,System.out.println(a.get("a")==b.get("a"));//false

所以所有相同类型的包装类对象之间值得比较,全部使用equals方法。

有poJAVA源码参考的博客https://blog.csdn.net/so_geili/article/details/79720238

猜你喜欢

转载自www.cnblogs.com/blairwaldorf/p/9194724.html