For some reason Java lets you define arrays like in C, adding the []
modifier after the variable or method name. That, however, is not possible with generics.
Generic type arguments have to be declared right with the type, because they are part of the type descriptor. Arrays should also be declared that way, as they are also part of the type descriptor.
In order to understand why the compiler does not let you write things that way (and why it shouldn't let you write things like in the first examples), we need to break it down to pieces.
public int returnArray()[] { ... }
public
: Visibility declarationint
: Return type, integerreturnArray
: Method name()
: Argument list (empty)[]
: Whoops! the return type is actually an arrayof what we said before
This is even better:
public String[] returnArray(String[] array[])[]
public
: Visibility declarationString[]
: Return type, an array of stringsreturnArray
: Method name(String[] array[])
: Argument list...String[]
: Type of the argument, array of stringsarray
: Name of the argument[]
: Whoops! argument type is actually an array of what we said before
[]
: Whoops again! return type is actually an array of what we said before
Foot note: Don't do this, specify the types only in the types. Instead of String[] array[]
, use String[][] array
.
Now that the array thing syntax is clear, and I hope you understand why it should be wrong, let begin with the generig thing:
public <T> List<T> rerurnList(List<T> list) { ... }
public
: Visibility declaration<T>
: This method uses generic typeT
List<T>
: Return type, a genericList
ofT
rerurnList
: Method name(List<T> list)
: Argument listList<T>
: Argument type, genericList
ofT
list
: Argument name