我使用的是 Android Studio 3.1.2,API 级别为 26,最低 API 为 21。我检查并发现包 android.util
的类型为 MutableDouble
,其实现如下:
package android.util;
/**
*/
public final class MutableInt {
public int value;
public MutableInt(int value) {
this.value = value;
}
}
但是当我使用特定输入值初始化 MutableDouble
的新实例时,它总是收到如下所示的零值:
MutableDouble d = new MutableDouble(999d);
System.out.println("Received value: " + d.value);
=> "Received value: 0.0"
我必须直接设置值才能使其工作
MutableDouble d = new MutableDouble(999d);
d.value = 777d;
System.out.println("Received value: " + d.value);
=> "Received value: 777.0"
我已将上述 MutableDouble
的实现复制到我自己的项目中,并且它按预期工作。
检查其他类似的类,例如 MutableInt
、MutableFloat
等,它们也有同样的问题。
有人跟我一样遇到这个问题吗? Android Studio 中的任何错误配置会导致此问题吗?
最佳答案
我相信这些函数是deprecated ,因此在使用 Android Studio >= 3.1.0(Android P SDK)时将无法正常工作。我不知道为什么他们不推荐使用 MutableInt、MutableDouble 等类,但我认为这是因为通过引用传递文字对于异步应用程序来说可能非常危险,而且它们是非常很容易实现的类!我建议使用 AtomicLong 像这样:
AtomicLong d = new AtomicLong(Double.doubleToLongBits(99.9));
System.out.println("Double is set to " + Double.longBitsToDouble(d.longValue()));
通过引用传递会更更安全。
还有一个Guava如果您可以引入 Guava 包,则可以使用 AtomicDouble 类。
另一个想法是使用 AtomicLong 创建一个您自己的简单 AtomicDouble 类,如下所示:
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.Double.*;
class AtomicDouble extends Number {
private AtomicLong bits;
public AtomicDouble() {
this(0.0);
}
public AtomicDouble(double initialValue) {
bits = new AtomicInteger(doubleToLongBits(initialValue));
}
public final boolean compareAndSet(double expect, double update) {
return bits.compareAndSet(doubleToLongBits(expect),
doubleToLongBits(update));
}
public final void set(double newValue) {
bits.set(doubleToLongBits(newValue));
}
public final double get() {
return longBitsToDouble(bits.get());
}
public double doubleValue() {
return get();
}
public final float getAndSet(double newValue) {
return longBitsToDouble(bits.getAndSet(doubleToLongBits(newValue)));
}
public final boolean weakCompareAndSet(double expect, double update) {
return bits.weakCompareAndSet(doubleToLongBits(expect),
doubleToLongBits(update));
}
public float floatValue() { return (float) doubleValue(); }
public int intValue() { return (int) get(); }
public long longValue() { return (long) get(); }
}
关于Java VM 无法使用 `android.util.*` : Mutable classes cannot be initialized with value other than zero,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436096/