Java:如何定义基于Integer的自定义数据类型? [英] Java: How to define custom Integer-based data type?

查看:189
本文介绍了Java:如何定义基于Integer的自定义数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个与Integer完全相同的数据类型,我希望它能溢出并下溢到某些值。换句话说,我想设置Integer类的对象/实例的MAX_VALUE和MIN_VALUE。问题是MAX_VALUE和MIN_VALUE是常量,最后是Integer类。我该怎么办?

I need a data type that behaves completely like Integer with this difference that I want it to overflow and underflow to certain values. On the other words, I'd like to set the MAX_VALUE and MIN_VALUE of an object/instance of the Integer class. The problem is MAX_VALUE and MIN_VALUE are constant and Integer class in final. How should I approach?

推荐答案

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

You'll have to create your own wrapper class:

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
}

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

You need to decide whether you want one fixed pair of limits for the whole type, or whether each instance can have a different limit (and what that means when adding together two values with different limits etc).

这篇关于Java:如何定义基于Integer的自定义数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆