Java中的Integer類型數字的比較

直接上代碼。 

	@Test(expected = NullPointerException.class)
	public void testIntegerComparation() throws Exception {
		// 相同的字面常量直接用等號比較,結果爲【相等】
		assertTrue(100 == 100);		
		assertTrue(1000 == 1000);
		
		// 兩個變量,值相同,用等號比較,結果爲【相等】
		Integer a = 100;
		Integer b = 100;
		assertTrue(a == 100);
		assertTrue(b == 100);
		assertTrue(a == b);
		
		// 兩個變量,值相同,將上面的100換成128。
		// 用不等號比較,結果爲【不相等】,爲什麼?
		Integer c = 128;
		Integer d = 128;
		assertTrue(c == 128);
		assertTrue(d == 128);
		assertTrue(c != d);
		
		// 用equals方法比較,結果【相等】
		assertTrue(a.equals(b));
		assertTrue(c.equals(d));
		
		// 用Integer.compare比較,結果【相等】
		assertTrue(Integer.compare(a, b) == 0);
		assertTrue(Integer.compare(c, d) == 0);
		assertTrue(a.compareTo(b) == 0);
		assertTrue(c.compareTo(d) == 0);
		
		// 如果有一個變量爲null,則equals可以用
		b = null;
		assertTrue(!a.equals(b));
		
		// 如果有一個變量爲null,則報NullPointerException
		assertTrue(Integer.compare(a, b) == 0);		
		assertTrue(a.compareTo(b) == 0);
	}

注意上面assertTrue(c != d)這一步,稍微不注意,就會在這裏犯錯誤。

總結:Integer類型變量的比較,只要有一個變量不爲null,則使用此變量的equals方法最可靠。但如果另一個變量爲null,此時Integer.compare靜態方法和實例方法都會報空指針異常。其次,如果兩個變量都不爲null, 則使用Integer.compare靜態或變量的compare實例方法也是可靠的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章