Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an Integer instance not nullable [duplicate]

Is there a way to ensure an Integer variable not to be null?

I need to create a list of integer values, so I cannot use int type. I need to work with a List<Integer> but this will allow null values for elements...

Do I need to use some particular implementation of List or is there some way to set Integer not nullable?

Note I need a List, not a Set.

like image 690
davioooh Avatar asked Jul 31 '26 12:07

davioooh


1 Answers

You could override the add method of a List and check whether the element is null.

new LinkedList<Integer>() {
    @Override
    public boolean add(Integer e) {
        if(e == null)
            return false;
        return super.add(e);
    }
};

You may need to add this check to the other insertion Methods like add(int pos, E value) or set(int pos, E value).

like image 195
succcubbus Avatar answered Aug 02 '26 01:08

succcubbus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!