【问题标题】:Byte with Integer comparsion not working整数比较的字节不起作用
【发布时间】:2017-01-03 16:55:23
【问题描述】:

我有简单的代码片段

getMarkerCode() == -1 ? null : getMarker(getMarkerCode());

其中getMarkerCode() 总是返回-1(字节类型)。但是每次都运行getMarker(getMarkerCode())方法。

即使将条件修改为:

if(getMarkerCode() == (byte)-1)
    return null;
else
    return getMarker(getMarkerCode());

结果没有改变。怎么了?

不包装到Byte 类是否可行?

Byte.compare(byte, byte) 需要 SDK >= 19,但应用程序支持 API 级别 16

【问题讨论】:

    标签: android ternary-operator


    【解决方案1】:

    Referring to this post 你应该使用compareTo 使用字节而不是字节作为@Sergey 在评论中指出。您可以轻松地做到这一点,因为您是“手动”进行实例化的,因此更改类型不会有任何问题。

    比字节可能应该像new Byte("-1") 一样被实例化

    new Byte("-1").compareTo(getMarkerCode()) == 0 ? null : getMarker(getMarkerCode());
    

    结果是:

    Returns           | Meaning
    --------------------------------------------------------------------
    0                 |   if this Byte is equal to the argument Byte;
    less than 0       |   if this Byte is numerically less than the argument Byte;
    greater than 0    |   if this Byte is numerically greater than the argument Byte (signed comparison).
    

    注意

    从字节到字节你可以简单地转换

    byte b; 
    //plus instantiating
    //...
    Byte bObj = b;
    

    【讨论】:

    • compareTo Byte 类的方法成员。原始类型byte 不包含此
    • @Sergey 谢谢!我没想到,我编辑了答案
    • 谢谢,码头!但我希望比较值而不包装到 Byte 类。有可能吗?你的解决方案不是秘密:)
    • @Sergey true,但是你知道,这里有人问如何做 1+1,所以我尝试了:P Aaaaanyway。你试过((int)getMarkerCode()) == -1吗?
    • 感谢您的工作,皮尔。我是solved问题
    【解决方案2】:

    正如我所料,问题在于 Android Studio 中的 Instant Run 选项。我禁用它,问题就消失了。

    注意即时运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多