2

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?

0

2 Answers 2

7

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).

Sign up to request clarification or add additional context in comments.

2 Comments

The whole type has fixed limit so no issues with what you mentioned. My only question remained (might be a little bit stupid) is if it's possible to define operators like "+" instead of "add"?
@Pouya: No, Java doesn't support operator overloading.
3

Since java.lang.Integer is final you cannot extend it. The only choice is to wrap it:

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

etc, etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.