簡體   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