2010-12-19 148 views
11
long a = 1111; 
Long b = 1113; 

if(a == b) 
{ 
    System.out.println("Equals"); 
}else{ 
    System.out.println("not equals"); 
} 

上面的代碼在控制檯中輸出「equals」,這是錯誤的答案。我的問題是如何比較長變量值是否等於Long變量值。請儘快重播我。如何比較long值等於Long值

Thankh你

+7

此代碼不會編譯。第二行需要很長的值,並且您提供了一個int。它應該是長b = 1113L;即便如此,它確實打印出正確答案。 – 2010-12-19 16:01:40

回答

26

首先你的代碼沒有編譯。 Long b = 1113;

是錯誤的。你不得不說

Long b = 1113L; 

其次,當我解決了這個問題彙編代碼印有「不等於」。

9

它按預期工作,

嘗試檢查IdeOneDemo

public static void main(String[] args) { 
     long a = 1111; 
     Long b = 1113l; 

     if (a == b) { 
      System.out.println("Equals"); 
     } else { 
      System.out.println("not equals"); 
     } 
    } 

打印

not equals

使用compareTo()來比較長,==將無法​​在所有情況下工作,只要值被緩存

+1

你說得對,但在這種情況下並不重要。 Autoboxing完成其工作。 – AlexR 2010-12-19 16:05:20

+2

@AlexR Auto * un *裝箱。如果自動複製'1234L'和'Long.valueOf(1234L)'*可能不相等。與引用一樣,如果'b'爲'null',它就會爆炸。 (哦,大寫L後綴是首選,因爲很難誤認爲1)。 – 2010-12-19 18:58:59

+2

longs不能與==比較。該理論指出,你需要使用一個簡單的技巧,比如從另一箇中減去一個,並查看相關的差異。 – hephestos 2012-12-26 14:28:06

7
long a = 1111; 
Long b = new Long(1113); 

System.out.println(b.equals(a) ? "equal" : "different"); 
System.out.println((long) b == a ? "equal" : "different"); 
3

一方面long是一個對象,另一方面long是一個原始類型。爲了比較它們,你可以得到基本類型出長型:

public static void main(String[] args) { 
    long a = 1111; 
    Long b = 1113; 

    if ((b!=null)&& 
     (a == b.longValue())) 
    { 
     System.out.println("Equals"); 
    } 
    else 
    { 
     System.out.println("not equals"); 
    } 
} 
1

我將分享如何做呢,因爲Java的7 -

Long first = 12345L, second = 123L; 
System.out.println(first.equals(second)); 

輸出返回:匹配的假

和第二個例子是 -

Long first = 12345L, second = 12345L; 
System.out.println(first.equals(second)); 

輸出返回:真

所以,我相信等於比較對象的值的方法,希望它可以幫助你,謝謝。

0
public static void main(String[] args) { 
     long a = 1111; 
     Long b = 1113L; 
     if(a == b.longValue()) 
    { 
     System.out.println("Equals"); 
    }else{ 
     System.out.println("not equals"); 
    } 
    } 

or: 

    public static void main(String[] args) { 
     long a = 1111; 
     Long b = 1113L; 
     if(a == b) 
    { 
     System.out.println("Equals"); 
    }else{ 
     System.out.println("not equals"); 
    } 
    } 
相關問題