Java 里面的 == 和equals的坑是在是太多了,即使做了多年java开发的程序员也不一定就能准确说出 a == b 或 a.equals(b) 这样简单的问题的答案。
请看下面这26道关于Long 和 bigdecimal 的相等比较,看看你是否可以准确说出每行代码的输出结果呢?
答案在文末,请先看题:
关于Long的相等比较:
1、System.out.println(Long.valueOf("9999999").equals(new Long(9999999L))); 输出:true/false?
2、System.out.println(Long.valueOf("9999999") == new Long(9999999L)); 输出:true/false?
3、System.out.println(Long.valueOf("1") == new Long(1L)); 输出:true/false?
4、System.out.println(1L == new Long(1L)); 输出:true/false?
5、System.out.println(new Long(1L) == new Long(1L)); 输出:true/false?
6、System.out.println(999999L == new Long(999999L)); 输出:true/false?
7、System.out.println(999999L == Long.valueOf("999999")); 输出:true/false?
8、System.out.println(Long.valueOf("999999") == Long.valueOf("999999")); 输出:true/false?
9、System.out.println(Long.valueOf("1") == Long.valueOf("1")); 输出:true/false?
10、System.out.println(Long.valueOf("127") == Long.valueOf("127")); 输出:true/false?
11、System.out.println(Long.valueOf("128") == Long.valueOf("128")); 输出:true/false?
12、System.out.println(Long.valueOf("-128") == Long.valueOf("-128")); 输出:true/false?
13、System.out.println(Long.valueOf("-129") == Long.valueOf("-129")); 输出:true/false?
关于BigDecimal的相等比较:
1、System.out.println(BigDecimal.valueOf(0) == BigDecimal.ZERO); 输出:true/false?
2、System.out.println(BigDecimal.valueOf(new Long(0)) == BigDecimal.ZERO); 输出:true/false?
3、System.out.println(BigDecimal.valueOf(0.0) == BigDecimal.ZERO); 输出:true/false?
4、System.out.println(BigDecimal.valueOf(0) == BigDecimal.valueOf(0)); 输出:true/false?
5、System.out.println(BigDecimal.valueOf(11) == BigDecimal.valueOf(11)); 输出:true/false?
6、System.out.println(BigDecimal.valueOf(10) == BigDecimal.valueOf(10)); 输出:true/false?
7、System.out.println(BigDecimal.valueOf(11).equals(BigDecimal.valueOf(11))); 输出:true/false?
8、System.out.println(BigDecimal.valueOf(9999).equals(BigDecimal.valueOf(9999))); 输出:true/false?
9、System.out.println(BigDecimal.valueOf(9999.00).equals(BigDecimal.valueOf(9999.00))); 输出:true/false?
10、System.out.println(BigDecimal.valueOf(9999.0).equals(BigDecimal.valueOf(9999.00))); 输出:true/false?
11、System.out.println(BigDecimal.valueOf(9999.0).equals(new BigDecimal(9999.00))); 输出:true/false?
12、System.out.println(BigDecimal.valueOf(0.0).equals(BigDecimal.ZERO)); 输出:true/false?
13、System.out.println(BigDecimal.valueOf(9999.0).compareTo(new BigDecimal(9999.00)) == 0); 输出:true/false?
答案来了
10
9
8
7
6
5
4
3
2
1
请看答案:
Long
1、System.out.println(Long.valueOf("9999999").equals(new Long(9999999L))); 输出:true
2、System.out.println(Long.valueOf("9999999") == new Long(9999999L)); 输出:false
3、System.out.println(Long.valueOf("1") == new Long(1L)); 输出:false
4、System.out.println(1L == new Long(1L)); 输出:true
5、System.out.println(new Long(1L) == new Long(1L)); 输出:false
6、System.out.println(999999L == new Long(999999L)); 输出:true
7、System.out.println(999999L == Long.valueOf("999999")); 输出:true
8、System.out.println(Long.valueOf("999999") == Long.valueOf("999999")); 输出:false