java - 将 BigInteger 与 Realm Java 一起使用?

标签 java android realm biginteger

Realm Java 不支持 BigInteger,因此以下类:

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

   ...

   public BigInteger getBonus() {
    return bonus;
   }

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

结果不支持类型为“java.math.BigInteger”的字段“value”。

我使用 Realm 的方式如下: bnsInitial.setBonus(new BigInteger("0")); 或类似 int x = bns.getBonus().compareTo(new BigInteger("0"));例如。

有没有办法让 BigInteger 与 Realm 一起使用?这些值有可能定期超过 Long 限制,这就是我使用 BigInteger 代替的原因。 谢谢

最佳答案

我的建议是:

  • 使用Stringbyte[]作为大整数的 Realm 表示,并在这些类型和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更有效,因为对于足够大的整数,转换速度会更快。 (文本 <-> 以 10 为基数和以 2^N 为基数之间的二进制转换将需要很长的乘法和除法。)

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

关于java - 将 BigInteger 与 Realm Java 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288389/

相关文章:

java - 如何在 java 中转换泛型列表类型?

java - Android Spinner 每行的不同背景

android - 如何使用 scrypt 生成 256 位 key ?

android - 使用DataBinding库设置背景色资源或为null

ios - 如何获取某个 Realm 对象在 Results 中的索引?

java - 在为用户打印代码之前,java是否会创建所有用于递归的堆栈帧?

java - Android Twitter 字符串转 Json 数组

java - 如何调用采用 "Collection<? extends T>"参数的方法?

ios - Realm :在对象的新插入/更新时得到通知

android - 如何将数据从Sqlite迁移到Realm