What is the purpose of List<Void>?

孤街浪徒 提交于 2019-12-03 01:01:48

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

I agree, it's odd.

I can see a use for it if you want to extend a generic class and return void from a method. I've bumped into a case were I want to use int and had to use Integer because java generics don't like primitive types.

public interface ObjectUserPool<E, T> {
    public E useObject(T o);
}

public class NonReturningObjectUserPool extends ObjectUserPool<Void, Integer> {
    public Void useObject(Integer i);
}

I think this is what the java API is saying, though to be honest I can't really find a use for NonReturningObjectUserPool.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!