當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Integer equals()用法及代碼示例


equals() 方法是java.lang 包下Integer 類的一個方法。此方法將參數的值與當前 Integer 對象的值進行比較。它返回布爾值(True 或 False),它對應於這個 Integer 和方法參數對象的相等性。它還覆蓋了 Object 類的 equals() 方法。

用法:

以下是 equals() 方法的聲明:

public boolean equals(Object obj)

參數:

數據類型 參數 描述 必需/可選
Object obj 它檢查與指定整數的相等性 Required

返回值:

如果參數不為空並且整數對象與方法參數對象相同,則 equals() 方法將返回真,否則將返回假。

異常:

輸入不匹配異常

兼容版本:

Java 1.2 及以上

例子1

public class IntegerEqualsExample1 {
	public static void main(String[] args) {		
	    Integer obj1 = new Integer(43);
	    Integer obj2 = new Integer(78);
	    System.out.print("obj1 and obj2 are equal. True or False? = ");
	    System.out.println(obj1.equals(obj2));   			    
	    obj1 = new Integer(55);
	    obj2 = new Integer(55);
	    System.out.print("obj1 and obj2 are equal. True or false? = ");
	    System.out.println(obj1.equals(obj2));	    	     
	}
}

輸出:

obj1 and obj2 are equal. True or False? = false
obj1 and obj2 are equal. True or false? = true

例子2

import java.util.Scanner;
public class IntegerEqualsExample2 {
	public static void main(String[] args) {		
		Scanner readInput = new Scanner(System.in);
		System.out.print("Input the first Integer Number to be Compare:");
		Integer intComp1 = readInput.nextInt();
		System.out.print("Input the second Integer Number to be Compare:");
		Integer intComp2 = readInput.nextInt();
		boolean Result = intComp1.equals(intComp2);
		if (Result){			 
            System.out.println("Both the Integer numbers are same...");
            }
		else {
			System.out.println("Both the Integer numbers are different...");
			}
		readInput.close();
	}
}

輸出:

1.	Input the first Integer Number to be Compare:34
Input the second Integer Number to be Compare:34
Both the Integer numbers are same...

2.	Input the first Integer Number to be Compare:45
Input the second Integer Number to be Compare:87
Both the Integer numbers are different...

例子3

public class IntegerEqualsExample3 {
	public static void main(String[] args) {	
	  Integer objA = 20;		 
        Integer objB = 20;
        Integer objC = 10;
        System.out.println("objA == objB? " + objA.equals(objB));
        System.out.println("objB == objC? " + objB.equals(objC));
        System.out.println("objA == objC? " + objA.equals(objC));
        System.out.println("objC == objA? " + objC.equals(objA));
        System.out.println("objB == objA? " + objB.equals(objA));      
      }
}

輸出:

objA == objB? true
objB == objC? false
objA == objC? false
objC == objA? false
objB == objA? true

示例 4

public class IntegerEqualsExample4 {
	public static void main(String[] args) {	
	  Float ObjFloat = 55.55f;		 
        Double ObjDouble = 55.55d;
        System.out.println("ObjFloat == ObjDouble? " +ObjFloat.equals(ObjDouble));    
	}
}

輸出:

ObjFloat == ObjDouble? false






相關用法


注:本文由純淨天空篩選整理自 Java Integer equals() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。