在 Realm Java 中使用 BigInteger?

Using BigInteger with Realm Java?

Realm Java 不支持 BigInteger 所以下面的 class:

public class Bonus extends RealmObject {
   String thebonus;
   BigInteger bonus;

   ...

   public BigInteger getBonus() {
    return bonus;
   }

   public void setBonus(BigInteger newBonus) {
    this.bonus = newBonus;
   }
}

字段 "value" 中 "java.math.BigInteger" 类型的结果不受支持。

我像这样使用 Realm: bnsInitial.setBonus(new BigInteger("0")); 或类似 int x = bns.getBonus().compareTo(new BigInteger("0")); 的东西。

有没有办法让 BigInteger 使用 Realm?这些值有可能经常超过 Long 限制,这就是我使用 BigInteger 的原因。 谢谢

我的建议是:

  • 使用 Stringbyte[] 作为大整数的领域表示,并在这些类型和 BigInteger 之间即时转换。
  • 如果你想在你的 RealmObject 中缓存一个 BigInteger 对象,然后使用 @Ignore 注释告诉 Realm 基础结构不要尝试传递它。

像这样:

public class Bonus extends RealmObject {
   byte[] thebonus;

   @Ignore
   BigInteger bonus;

   public BigInteger getBonus() {
       if (bonus == null) {
           bonus = new BigInteger(thebonus);
       } 
       return bonus;
   }

   public void setBonus(BigInteger newBonus) {
       bonus = newBonus;
       thebonus = BigInteger.toByteArray();
   }
}

使用 byte[]String 更有效,因为转换速度更快……对于足够大的整数。 (Text <-> base 10 和 base 2^N 之间的二进制转换将需要很长的乘法和除法。)

免责声明:本文仅基于阅读 documentation。我从未使用过 Realm。