【问题标题】:Comparison between two longs doesn't work as expected [duplicate]两个多头之间的比较没有按预期工作[重复]
【发布时间】:2015-05-28 08:06:18
【问题描述】:

这将是一个简单的问题(或者至少我认为)。我必须将 Long 对象与 long 原语进行比较。

我的代码简化了:

long primitiveLong = 285825645621;
Long objectLong = new Long(285825645621);

if(primitiveLong == objectLong.longValue()){
    System.out.print("They are equals");
}

我希望它会起作用,但它没有,谁能解释我为什么?

提前致谢。

编辑

好的,我用明确的数字犯了一个错误,我会把我的代码放在这里:

long identifier = mMarkers.get(marker);
long currentId = item.getId().longValue();

if (currentId==identifier)
    System.out.print("They are equals");

调试中

编辑 2

这是调试模式下的 IDE (Android Studio) 错误,我在另一个 IDE 上尝试过,它在相同的代码下运行良好。所以感谢大家的回答,但问题是另一个我无法预料的问题。

【问题讨论】:

  • 代码是否进入了 if 循环,或者我们应该猜测一下你认为应该发生的事情:)
  • @ChetanKinger if 语句中应该已经输入了代码
  • 它不会编译,编译时在数字末尾添加 L,那么这段代码应该可以正常工作 @ChetanKinger if 不是循环而是语句;)

标签: java numbers


【解决方案1】:

首先这应该会给你编译错误,因为编译器认为285825645621 是一个整数,但它大于整数,所以你需要像这样更改你的代码:

long primitiveLong = 285825645621l; //add and l at the end of your number so compiler know that it is a long not an int
Long objectLong = new Long(285825645621l); //do the same thing here

if(primitiveLong == objectLong.longValue()){
    System.out.print("They are equals");
}

这将打印:They are equals

【讨论】:

  • 正如我所说,这是我的代码的更简化版本。我没有明确的数字,而是返回它们的方法
  • @Fondesa 所以你不能很好地简化你的代码!请提供更多信息,根据您提供的数据,我无法解释为什么会发生这种情况。
  • 查看对我的问题的修改!
  • @Fondesa 你确定你现在提供正确的数据吗?它们都是 long 具有相同的值,所以 == 应该可以工作!
【解决方案2】:

你可以使用你的文字值仍然这个限制285825645

If you are using beyond the limit you will get compile error 

long primitiveLong = c;
            Long objectLong = new Long(285825645);

            if(primitiveLong == objectLong.longValue()){
                System.out.print("They are equals");
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-15
    • 2019-11-27
    • 1970-01-01
    • 2018-01-21
    • 2013-01-31
    • 2016-11-09
    • 2020-01-03
    • 1970-01-01
    相关资源
    最近更新 更多