繁体   English   中英

Java:如何定义基于Integer的自定义数据类型?

[英]Java: How to define custom Integer-based data type?

我需要一个与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是final,因此无法扩展它。 唯一的选择是包装它:

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

等等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM