I'm trying to use the charts4j
api and one of the constructors has this:
public static Data newData(List<? extends Number> data)
It looks like some form of generics to me, but I've never seen this notation before and I don't understand it.
I'm trying to use the charts4j
api and one of the constructors has this:
public static Data newData(List<? extends Number> data)
It looks like some form of generics to me, but I've never seen this notation before and I don't understand it.
This is an upper-bounded wildcard: ? extends Number
.
It means that data
can be a list of anything that is Number
or a subclass, such as List<Number>
, List<Integer>
, List<Double>
, etc.
Generics in Java are not covariant, so a List<Double>
is not a List<Number>
. Here, a parameter of type List<? extends Number>
allows List<Double>
as well as List<Number>
, but a parameter of type List<Number>
does not allow List<Double>
.
As for the List
part, it could be anything that implements List
, such as LinkedList<Integer>
or ArrayList<Double>
.
public static Data newData(List<? extends Number> data)
This defines a method that receives a collection implementing the List
interface (ArrayList
, for example), that contains any subclass of the Number
class (even the Number
class itself).
Indeed, this concept is related to generics and it's called an Upper Bounded Wildcard. Long story short: It allows you to write a method without a specific type restriction, but a hierarchy restriction instead.
Yes it is wildcard in generics. It means the method will accept any List of type of class that extends Number.
Example: List<Integer>, List<Double>
<T extends SomeClass>
is used when the actual parameter can be some class or any sub class of it. So in your case:
public static Data newData(List<? extends Number> data)
your method can accept a list of any class that is of type Number.
To learn more about Java generics refer:
http://docs.oracle.com/javase/tutorial/extra/generics/methods.html
It is a generic type. It means that the data
parameter is a List of any class that extends Number. i.e. If you have a custom class:
public class Nomber extends number {
//stuff...
}
it will take a List<Nomber>
as a variable.
It means that the data list can only add a object of Number type or SubNumber type as Double, Integer...