'What does a generic type before the type name in a constructor call mean?
What does the code mean like this?
new <Number>ArrayList()
I know the correct way to write it like this
new ArrayList<Number>()
The first is not a generic, but what does it mean?
Solution 1:[1]
It's the type argument of function new
// Different type is semantic bad but good for testing the AST
final List<String> ls = new<Integer> ArrayList<Double>();
AST:
{
"node": "VariableDeclarationFragment",
"name": {
"identifier": "ls",
"node": "SimpleName"
},
"extraDimensions": 0,
"initializer": {
"arguments": [],
"anonymousClassDeclaration": null,
"node": "ClassInstanceCreation",
"type": {
"node": "ParameterizedType",
"type": {
"node": "SimpleType",
"name": {
"identifier": "ArrayList",
"node": "SimpleName"
}
},
"typeArguments": [
{
"node": "SimpleType",
"name": {
"identifier": "Double",
"node": "SimpleName"
}
}
]
},
"typeArguments": [
{
"node": "SimpleType",
"name": {
"identifier": "Integer",
"node": "SimpleName"
}
}
],
"expression": null
}
}
Solution 2:[2]
These are the type arguments to a generic constructor
A generic constructor declaration defines a set of constructors, one for each possible invocation of the type parameter section by type arguments. Type arguments may not need to be provided explicitly when a generic constructor is invoked, as they can often by inferred
You can have generic constructors for non-generic classes, and generic constructors for generic classes that do not share a generic type with their class.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Patrick Haugh |
