【发布时间】:2012-03-19 19:16:49
【问题描述】:
我需要一个行为完全像整数的数据类型,但我希望它上溢和下溢到某些值。换句话说,我想设置 Integer 类的对象/实例的 MAX_VALUE 和 MIN_VALUE。问题是 MAX_VALUE 和 MIN_VALUE 是常量,最终是 Integer 类。我应该如何接近?
【问题讨论】:
我需要一个行为完全像整数的数据类型,但我希望它上溢和下溢到某些值。换句话说,我想设置 Integer 类的对象/实例的 MAX_VALUE 和 MIN_VALUE。问题是 MAX_VALUE 和 MIN_VALUE 是常量,最终是 Integer 类。我应该如何接近?
【问题讨论】:
您必须创建自己的包装类:
public class CustomInteger
{
public static final int MAX_VALUE = 5000;
public static final int MIN_VALUE = -5000;
private final int value;
public CustomInteger(int value)
{
// TODO: Validation
this.value = value;
}
// Add all the methods you want - e.g. integer operations etc
// performing custom overflow/underflow on each operation
}
您需要决定是否要为整个类型设置一对固定的限制,或者每个实例是否可以有不同的限制(以及将具有不同限制的两个值相加时的含义等)。
【讨论】:
由于java.lang.Integer 是最终的,你不能扩展它。唯一的选择就是包装它:
public class LimitedInteger {
private int value;
private int min;
private int max;
LimitedInteger() {
}
LimitedInteger(int value) {
this.value = value;
}
LimitedInteger(int value, int min, int max) {
this.value = value;
this.min = min;
this.max = max;
}
}
等等等等
【讨论】: