How to make an Integer instance not nullable

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


asked Apr 20, 2015 in Core java by rajesh
0 votes

1 Answer

0 votes

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

new LinkedList<Integer>() {
    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).

answered Apr 20, 2015 by rajesh