3

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.

davioooh
  • 23,742
  • 39
  • 159
  • 250

5 Answers5

4

No, there is none. Simplest way is just to add a pre-check:

if (intVal != null) {
  list.add(intVal);
} else {
 // TODO: error handling
}

Anyway you'll have to handle an exception/return-value for your custom Data Structure, which doesn't allow NULLs.

Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129
4

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

succcubbus
  • 874
  • 1
  • 7
  • 24
1

Just to complete answers above. In case you are using java8 you can benefit from Optional class.

Al1en313
  • 151
  • 6
0

Use a Queue implementation, like LinkedBlockingQueue, many of them don't allow nulls.

Look at http://docs.oracle.com/javase/tutorial/collections/implementations/queue.html

I also recommend you to take a look at Lombok's NonNull annotation:

http://projectlombok.org/features/NonNull.html

Andres
  • 10,561
  • 4
  • 45
  • 63
0

You could try, after populating the List, to filter out the null values using the Google Guava Collections2.filter() method:

    List<Integer> myList = new ArrayList<Integer>();
    myList.add(new Integer(2));
    myList.add(null);
    myList.add(new Integer(2));
    myList.add(new Integer(2));
    myList.add(null);
    myList.add(new Integer(2));

    myList = new ArrayList<Integer>(Collections2.filter(myList, new Predicate<Integer>() {
        @Override
        public boolean apply(Integer integer) {
            return integer != null;
        }
    }));

    System.out.println(myList); //outputs [2, 2, 2, 2]
Gabriel Ruiu
  • 2,753
  • 2
  • 19
  • 23