Home > front end >  return type in method signature [duplicate]
return type in method signature [duplicate]

Time:09-17

I'm still learning about generics and have not fully gotten it, yet. Let us consider the following example taken from https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList-T...-

There, the method signature is

public static <T> List<T> asList(T... a)

Is the return type List<T>? Then, what is the meaning of the first <T>? (Why is it not public static List<T> asList(T... a)?)

CodePudding user response:

As mentioned in the comment it is a type parameter. You may wonder why this type parameter has to be mentioned explicitly in the beginning, and why it is not obvious that T is one, even without mentioning it in the beginning as <T>.

The reason for this may become more obvious when you have a look at the following example:

<T extends List<?>> T extractFirstNestedList(Collection<T> nestedList) {
  return nestedList.iterator().next();
}

With this you can define that the type parameter T must be a list (or any sub-class of a List). So have a look at the following examples:

This works...

extractFirstNestedList(Collections.singleton(Collections.singletonList("MyWorkingSample")));

and would return:

Collections.singletonList("MyWorkingSample")

whereby...

extractFirstNestedList(Collections.singleton(Collections.singleton("NotWorking")));

does not work since the Collection (more precise Set) does not have a nested List.

I hope this example motivates the usage of type parameters and why they are defined explicitly.

  • Related