【问题标题】:Java: How to define custom Integer-based data type?Java:如何定义自定义的基于整数的数据类型?
【发布时间】:2012-03-19 19:16:49
【问题描述】:

我需要一个行为完全像整数的数据类型,但我希望它上溢和下溢到某些值。换句话说,我想设置 Integer 类的对象/实例的 MAX_VALUE 和 MIN_VALUE。问题是 MAX_VALUE 和 MIN_VALUE 是常量,最终是 Integer 类。我应该如何接近?

【问题讨论】:

    标签: java types integer


    【解决方案1】:

    您必须创建自己的包装类:

    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
    }
    

    您需要决定是否要为整个类型设置一对固定的限制,或者每个实例是否可以有不同的限制(以及将具有不同限制的两个值相加时的含义等)。

    【讨论】:

    • 整个类型有固定的限制,所以你提到的没有问题。我唯一剩下的问题(可能有点愚蠢)是是否可以定义像“+”这样的运算符而不是“add”?
    • @Pouya:不,Java 不支持运算符重载。
    【解决方案2】:

    由于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;
        }
    }
    

    等等等等

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多