What is the purpose of List<Void>? What is the purpose of List<Void>? java java

What is the purpose of List<Void>?


It is possible that this method signature was created as a by-product of some generic class.

For example, SwingWorker has two type parameters, one for final result and one for intermediate results. If you just don't want to use any intermediate results, you pass Void as the type parameter, resulting in some methods returning Void - i.e. nothing.

If there were a method List<V> returnAllIntermediateResults() in SwingWorker with Void as the type parameter V, it would have created a method just like you posted in your question.

The code would be perfectly valid. You can instantiate any implementation of the List interface (e.g. ArrayList) with type parameter Void. But the only value a Void type can have is null. So the list could not hold anything else but nulls, if the implementation allows null elements.


One case in which it may be useful is if you wanted to return a collection of return values from a function. Say

static List<T> forEach(Func<A,T> func, List<A> items) {   List<T> ret = new List<T>();   for(int i = 0; i< items.length; i++) {     ret.add(func.call(items[i]);   }   return ret;}public static void main() {  ...  List<Void> boringResult =    forEach(    new Func<Void, Integer> {@override Void call(Integer i) {...}});}

Not that useful but you could see a case where it was required.


List<Void> is weird. It can only have null elements, since you can't create an object of type Void. I don't think there is a practical use for such a thing.

Void is part of java.lang. It's not a special keyword or anything. It's a "pseudo-type" (according to the docs) used to as a place-holder to represent the Class object corresponding to void, as in Class<Void>. From the docs for Class:

The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

The Void class exists mainly for the sake of the last part of this, so you can write:

Class<Void> voidType = void.class; // == Void.TYPE

just like you can write:

Class<Integer> intType = int.class; // == Integer.TYPE