What does this syntax mean (List<? extends Number> data) [duplicate] - java

This question already has answers here:
What does the question mark in Java generics' type parameter mean? [duplicate]
(6 answers)
Closed 9 years ago.
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...

Related

What does <T extends Comparable<T>> mean? [duplicate]

This question already has answers here:
Java- The meaning of <T extends Comparable<T>>?
(7 answers)
Closed 3 years ago.
I was looking over the TheAlgorithms repository for java and came to this first: https://github.com/TheAlgorithms/Java/blob/master/Searches/SearchAlgorithm.java. I see <T extends Comparable<T>>, and I don't know what this means. I only know a little bit about generics and I know that the syntax has something to with parameter type bounds, but it would be great if someone could clarify how this has to do with Comparable<T>, and what Comparable<T> is.
There are some other questions on this forum similar to mine dealing with implementing <T extends Comparable<T>>, but the answers haven't really clarified what Comparable<T> is.
First, you have the Comparable interface which roughly looks like:
public interface Comparable<T> {
int compareTo(T other);
}
As you can see, the type parameter of Comparable is used as the parameter of the compareTo method. Typically, the type argument for T is the same class which is implementing the Comparable interface. This generic setup facilitates comparing instances of the same type with each other. Here's an example:
public class Name implements Comparable<Name> {
#Override
public int compareTo(Name other) {
// compute & return result
}
}
Now let's say you have a method which should return the maximum of two objects according to their natural order. Such a method could look like the following:
public static <U extends Comparable<U>> U max(U left, U right) {
return left.compareTo(right) >= 0 ? left : right;
}
Note: Used U as the type variable instead of T to show it is separate from the T used in the Comparable interface.
The above is a generic method. The type variable U is upper-bounded by Comparable<U>. What this means is that the type argument used in place of U must be assignable to (i.e. subtype of) Comparable<U>. For instance, if we use Name as the type argument it will work because Name is assignable to Comparable<Name>. The reason for specifying the upper-bound as Comparable<U> is that the method needs to call compareTo in order to function properly.
Name name1 = ...;
Name name2 = ...;
Name max = max(name1, name2); // U is inferred to be Name
As shown above, having U as the return type also allows assigning the result to a variable of the same type as the arguments.
Note that for maximum flexibility the max method should actually be declared like so:
public static <U extends Comparable<? super U>> U max(U left, U right) {
return left.compareTo(right) >= 0 ? left : right;
}
The difference being the use of Comparable<? super U> as the upper-bound instead of Comparable<U>. These two Q&As should help explain why using ? super U offers greater flexibility:
What is PECS (Producer Extends Consumer Super)?
Explanation of generic <T extends Comparable<? super T>> in collection.sort/ comparable code?
To clarify, we can decompose this puzzling-looking expression into its elements and put them back together.
Premise
We have a method find(? array[], ? key) that looks for a key within an array. We want to use this method for different types of input arguments, e.g., an array/key of String, Integer, whatever.
Parametric Type <U>
We put <U> in front of the method signature to indicate that it is a parametric method. This means that in the rest of the declaration, U is a placeholder that will be replaced by a type where the method is invoked. (I use U instead of T for reasons that will become obvious below.)
But, we can't replace U with any type because to be able to correctly implement the method, we want to be able to compare the elements in the array to each other (for instance to sort the array). The common interface used to define this behavior is Comparable. It has a single method, compareTo.
Type Bound <U extends Comparable>
To require that the U type parameter only be replaceable (instantiable) with a type that is a subtype of Comparable, we impose the type bound: extends Comparable. This allow us to call compareTo on key or on array elements such as array[0] in a type safe way.
However, we're not done here, because Comparable is itself a generic type: Comparable<T>, where the type parameter T governs the type of the parameter for compareTo. We thus need to instantiate T when we use Comparable<T>.
Instantiating Comparable<T>
Before instantiating T in Comparable, our expression is <U extends Comparable<T>>. We need to replace T with the desired type. What should be the type of the parameter to compareTo? If we are passing an array of String to find, we would be comparing Strings, etc. In the generic case we are passing an array of U to find, so we would like to compare objects of type U. So in this case we instantiate T in Comparable<T> with another generic type, U: <U extends Comparable<U>>, which is the same as <T extends Comparable<T>>
It means that T is a class type which is subtype of or inheriting Comparable which also accepts a generic type and it should be of same type as the class which is represented by T here.
E.g.
replace T by Employee class and Employee class definition is as below.
Employee is now T and Comparable's compareTo method must also accept Employee as parameter as T is now Employee per Comparable.
class Employee implements Comparable<Employee>{
#Override
public int compareTo(Employee o) {
return 0;
}
}

Java generilization is demanding implicit type instead wildcard

I have class:
public class WebDriverHighlighterListener extends AbstractWebDriverEventListener implements WebDriverEventListener {
And code
Why does it demand implicit type when I have constructor with wildcard?
There are two different issues. Before Java 8, the expression Arrays.asList(X) invariably has the type List<TypeOfX> which you refer to as “implicit type”.
This type is not assignment compatible with your wildcard.
Let’s explain it with a simple example. Suppose, we declare a variable of type
List<Class<String>> list=Arrays.asList(String.class);
This is a list, capable of holding instances of type Class<String> (there is only one, i.e. String.class) and nothing else.
In contrast, a list of type
List<Class<? extends CharSequence>> list2;
is allowing us to do all of these:
list2.add(StringBuilder.class);
list2.add(String.class);
list2.add(CharBuffer.class);
therefore, it should be clear, that we can’t assign list to list2 as then a list, allowing only String.class as it’s element, could suddenly get filled with these other Class<? extends CharSequence> objects.
If you want to have list, guaranteeing that the instances you will retrieve from it are of type Class<? extends CharSequence>, without constraining its actual type, i.e. being assignment compatible with List<Class<String>>, because you are not going to store new elements to the list, you can use
List<? extends Class<? extends CharSequence>> list3=list;// legal assignment
which allows
Class<? extends CharSequence> cl=list3.get(0);
but attempts to store new elements to list3 will be rejected by the compiler, because the actual element type of is unknown (Well, except for attempts to store null as it is legal for all reference types).
Alternatively you can use
List<Class<? extends CharSequence>> list4=Collections.unmodifiableList(list);
Because, it is known that the returned list will reject modifications at runtime, this kind of type conversion is accepted at compile-time.
Of course, you can also change the type of the Array.asList expression. This is the right way to go, when you are going to modify the list.
List<Class<? extends CharSequence>> list
= Arrays.<Class<? extends CharSequence>>asList(String.class);
Starting with Java 8, this type will get inferred automatically using the target type, thus the following is legal Java 8 code:
List<Class<? extends CharSequence>> list=Arrays.asList(String.class);
This also works when the Array.asList expression is an argument to a constructor invocation.
This all applies to AbstractWebDriverEventListener and WebDriverEventListener the same way it applies to String and CharSequence.

What's the difference between wildcard and 'T'? [duplicate]

This question already has answers here:
When to use wildcards in Java Generics?
(6 answers)
Closed 8 years ago.
public <? extends Animal> void takeThing(ArrayList<?> list)
public <T extends Animal> void takeThing(ArrayList<T> list)
Why this statement is wrong? I mean why the ? can't be used in the front? But T can. What is the difference?
Possible duplicate "When to use wildcards in Java Generics?"
Here is an answer for this question.But I don't get what this mean.
"if you say void then there is no return type. if you specify then there is a return type. i didn't know that you can specify to have return type or no return type."
Writing <T extends Animal> binds the type name T, so that it can be referred to later in the definition (including in the parameter list).
If you wrote <? extends Animal>, then you did not name the type. Therefore, you cannot refer to it later. You can't refer to it as ? later because that could be ambiguous (what if you had two type parameters?).
Java forbids you from writing public <?> ... because such a declaration is useless (the type parameter is not named so it cannot be used).
public void takeThing(ArrayList<? extends Animal> list)
means "do something with a list of any subclass of Animal".
public <T extends Animal> void takeThing(ArrayList<T> list)
means "do something with a list of some particular subclass (A.K.A. T) of Animal".
If I call list.get() on the first method, all I know about the returned type is that it extends Animal. On the second method, if I had another instance of List<T>, I know that whatever type T is, both lists would accept the same type.
To take it even further, if I say
Animal animal = list.get(0);
I can no longer say
list.add(animal);
even on the very same list, because we don't have a reference to the generic subtype. If however, I declare a List<T> where <T extends Animal>, I can now say
T animal = list.get(0);
list.add(animal);
because we know that list expects elements of type T.

Java Generics (bounded wildcards)

According to the book "Effective Java" of Joshua Bloch there is a rule about how/when use the bounded wildcards in generics. This rule is PECS (Producer-Extends, Comsumer-Super). When I study the following example:
Stack<Number> numberStack = new Stack<Number>();
Iterable<Integer> integers = ... ;
numberStack.pushAll(integers);
I understand that this rule fits perfect in this example. I have to declare the method pushAll as the following sample:
// Wildcard type for parameter that serves as an E producer
public void pushAll(Iterable<? extends E> src) {
for (E e : src)
{
push(e);
}
}
But what happens if I have the following example?
Stack<Integer> integerStack = new Stack<Integer>();
Iterable<Number> numbers = ... ;
integerStack.pushAll(numbers);
I have to declare the pushAll as it follows:
public void pushAll(Iterable<? super E> src) {
for (E e : src)
{
push(e);
}
}
According to PECS rule the above declaration is wrong. But I want to have a Stack of Integers and pass to this Stack a Number. Why not to do it?
Why should I always use the extends keyword? Why using super is wrong?
Of course the same stands for the comsumer's point of view. Why a consumer should always be super?
PS: To be more specific you can find this above example at the sector "Item 28" of the referred book.
When you declare a Stack<Foo> you mean a Stack of Foos, or subclasses of Foo. As an example, you would expect to be able to put a String in a Stack<Object>. The other way is not true, you should not be able to insert another Object, in a Stack<String>.
In your example you declare a Stack<Integer>. You should be able to put Integers in this stack, but not other Numbers (like a Double), which you would if you declared the parameter <? super E>. That's why the put-method should have a paramter of the type <? extends E>.
Trying to store arbitrary numbers in a Stack can't possibly work, since a Number could be something other that an Integer. So your example doesn't make much sense.
You would use super when the object asts as a consumer, i.e. when instances of the generic type of the object are passed as arguments to methods of the object. For example:
Collections.sort(List<T>, Comparator<? super T>)
In this example, the sort method takes T instances from the collection, and passes them as argument to the compare(T o1, T o2) of the comparator.
Contrast this to your first example, where the Iterable src is a producer. The pushAll() method calls a method of the Iterable which roduces (i.e. returns) instances of T. In this case, the iterable is a producer, hence the use of ? extends T
In the pushAll method, you are not passing type E, but any type that extends E. So, instead of passing an Iterable of Numbers, you can pass any Iterable of a type that extends Number.
The original example uses a Number type because you can then pass any type that is a subclass of Number, like Integer, BigDecimal and so on.
In your example, you are doing it the other way around. You are using Integer to declare your Stack. Therefore, pushAll will only be able to accept those classes that are extended by Integer. You will not be able to use Numbers (or any other class, because Integer is a final class).
First thing to notice is that Integer extends Number, so you shouldn't be pushing Number objects into a Stack of Integers. However, the first sample will work with Integers, Floats, BigDecimal and all other Number subclasses.
Your example doesn't make much sense. A construct like <? extends Number> means that Number and every type is allowed which inheits from Number. So you define an upper and a lower boundary, from type Number down to the most specific one. The other way round, <? super Number> means that Number and any of its supertyes are allowed. Since Number extends Object and implements Serializable the following three types are allowed:
java.lang.Number
java.lang.Object
java.io.Serializable
In your example you declare the generic type Stack<Integer>. Let's consider the following.
Your Stack is never be able to hold items of any super type of Integer
Your Stack is never be able to hold items of any subtype of Integer, since Integer class is final and thus it can't be subclassed.
So, if you want to declare the generic type Stack<Integer>, your iterable is of type Iterable<Integer> and thus your Stack can only hold items of type Integer. You are totally right with the mnemonic PECS, but this only works if you have choosen a concrete type which has at least one super type and at least one subtype.

What is <? super T> syntax? [duplicate]

This question already has answers here:
Difference between <? super T> and <? extends T> in Java [duplicate]
(14 answers)
Closed 6 years ago.
I'm having trouble understanding the following syntax:
public class SortedList< T extends Comparable< ? super T> > extends LinkedList< T >
I see that class SortedList extends LinkedList. I just don't know what
T extends Comparable< ? super T>
means.
My understanding of it so far is that type T must be a type that implements Comparable...but what is < ? super T >?
super in Generics is the opposite of extends. Instead of saying the comparable's generic type has to be a subclass of T, it is saying it has to be a superclass of T. The distinction is important because extends tells you what you can get out of a class (you get at least this, perhaps a subclass). super tells you what you can put into the class (at most this, perhaps a superclass).
In this specific case, what it is saying is that the type has to implement comparable of itself or its superclass. So consider java.util.Date. It implements Comparable<Date>. But what about java.sql.Date? It implements Comparable<java.util.Date> as well.
Without the super signature, SortedList would not be able accept the type of java.sql.Date, because it doesn't implement a Comparable of itself, but rather of a super class of itself.
It's a lower-bounded wildcard.
JLS 4.5.1 Type Arguments and Wildcards
Wildcards are useful in situations where only partial knowledge about the type parameter is required. [...] An upper bound is signified by the syntax:
? extends B
where B is the upper bound. [...] it is permissible to declare lower bounds on a wildcard, using the syntax:
? super B
where B is a lower bound.
A List<? super Integer>, for example, includes List<Integer>, List<Number>, and List<Object>.
Wildcards are used to make generics more powerful and flexible; bounds are used to maintain type safety.
See also
Java language guide/Generics/More Fun with wildcards
As to how this is useful in <T extends Comparable<? super T>>, it's when you have something like Cat extends Animal implements Comparable<Animal>.
Look at the signature of Collections.sort
public static <T extends Comparable<? super T>> void sort(List<T> list)
Therefore, with a List<Cat> listOfCat, you can now Collections.sort(listOfCat).
Had it been declared as follows:
public static <T extends Comparable<T>> void sort(List<T> list)
then you'd have to have Cat implements Comparable<Cat> to use sort. By using the ? super T bounded wildcard, Collections.sort becomes more flexible.
See also
Effective Java 2nd Edition, Item 28: Use bounded wildcards to increase API flexibility
Also, PECS principle: "producer extends consumer super"
It means that T must implement Comparable<T itself or one of T's superclasses>
The sense is that because SortedList is sorted, it must know how to compare two classes of its generics T parameter. That's why T must implement Comparable<T itself or one of T's superclasses>
It means that the type T must implement Comparable of T or one of its super classes.
For example, if A extends B, if you want to use SortedList<A>, A must implement Comparable<A> or Comparable<B>, or in fact just Comparable.
This allows the list of As to be constructed with any valid comparator.
Consider the following example:
Using a type parameter defined in the class declaration
public class ArrayList extends AbstractList ... {
public boolean add(E o) // You can use the "E" here ONLY because it's already been defined as part of the class
Using a type parameter that was NOT defined in the class declaration
public <T extends Animal> void takeThing(ArrayList<T> list)
// Here we can use <T> because we declared "T" earlier in the method declaration
If the class itself doesn't use a type parameter, you can still specify one for a method, by declaring it in a really unusual (but available) space - before the return type. This method says that T can be "any type of Animal".
NOTE:
public <T extends Animal> void takeThing(ArrayList<T> list)
is NOT same as
public void takeThing(ArrayList<Animal> list)
Both are legal, but they are different. The first one indicates that you can pass in a ArrayList object instantiated as Animal or any Animal subtype like ArrayList, ArrayList or ArrayList. But, you can only pass ArrayList in the second, and NOT any of the subtypes.

Categories

Resources