Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of List<Void>?

I didn't even know this was doable, but I saw while perusing some code online a method with a signature like this:

public List<Void> read( ... ) 

... What? Is there ever a reason to do this? What could this List even hold? As far as I was aware, it's not possible to instantiate a Void object.

like image 751
asteri Avatar asked Nov 22 '12 20:11

asteri


People also ask

What is the point of void?

When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."

What is the purpose of void in Java?

The void keyword specifies that a method should not have a return value.

Is void a data type in Java?

void is a type in the Java language (you can read that directly in the Java Language Specification). However the type void has no member values, that is no concrete value will ever have the type void.

Is void a keyword in Java?

void is a Java keyword. Used at method declaration and definition to specify that the method does not return any type, the method returns void .


2 Answers

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.

like image 105
Jakub Zaverka Avatar answered Oct 02 '22 18:10

Jakub Zaverka


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.

like image 39
David Waters Avatar answered Oct 02 '22 18:10

David Waters