I have couple of thoughts regarding the following:
public interface MaxStack<T extends Comparable <T>>
1-Why does the class that implements MaxStack should be written like this:
public class MaxStackclass<T extends Comparable <T>> implements MaxStack<T>
and not public class MaxStackclass<T extends Comparable <T>> implements MaxStack<T extends Comparable <T>>?
2- why do the private variables of this class, when I use generics, should be written only with <T> and not with <T extnds Comparable<T>>? For example, private List<T> stack= new ArrayList<T>();
3-What is the difference between <T extends Comparable<T>> and <T extends Comparable>- if I need to compare bewteen elements in my class, both will be O.K, no?
Edit: I think that thee problem with 3 is that maybe it allows to insert of a list that was defined in the second way to have different elements which all extends from comparable and then when I want to compare them, it won't be possible, since we can't compare String to Integer, both extend from Comparable.
In the declaration maxStackclass<T extends Comparable <T>> you have already expressed the bounds on T. So you do not need it again.
Reason same as above. No need to specify bounds on the same type parameter again.
<T extends Comparable<T>> means that T must implement the Comparable interface that can compare two T instances. While <T extends Comparable> means T implements Comparable such that it can compare two Objects in general. The former is more specific.
if I need to compare bewteen elements in my class, both will be O.K,
no?
Well, technically you can achieve the same result using both. But for the declaration <T extends Comparable> it will involve unnecessary casts which you can avoid using the type safe <T extends Comparable<T>>
1) the class has a type parameter T with a bound (extends Comparable <T>), this parameter is passed to the interface (which need the same bound here). When passing a type parameter, you must not repeat its bound - why you should do so?
2) like 1), the type parameter has its bound declared, no repeat neccessary.
To clarify:
The first type parameter occurence (here behind the interface or class name) is its declaration. Any following occurence is a usage. You even never would write a variables type declaration each time you use it, right?
"3-What is the difference between <T extends Comparable<T>> and <T extends Comparable>- if I need to compare bewteen elements in my class, both will be O.K, no?"
No, both will not be okay. Suppose I have a class Foo which implements Comparable<Bar> but classes Foo and Bar have no relation to each other. Then Foo cannot compare to other objects of type Foo. <T extends Comparable<T>> will catch this as a problem. <T extends Comparable> will not.
Related
Suppose I have a class
public static class A<T extends D> { ... }
and the class D with two classes extending it: B and C, e.g.
public static class D { ... }
public static class B extends D { ... }
public static class C extends D { ... }
Now, at some place let's say I want an array of A's, irrespective of being of the B-kind or the C-kind. (And apply functions from class D to all items in the array, for example.)
Should I then constrain the type again?
In other words: which of these options is the one to go with?
A<?>[] re;
A<? extends D>[] re;
Which one is best practice?
Since T has an upper bound of D, A<?> is just a shorthand for A<? extends D>. They both mean the same thing - just like if T were unbounded, A<?> would be short for A<? extends Object>.
I don't know of any best practice when it comes to this syntax; I think it's just a matter of coding style. I would prefer A<?> because it's concise, though A<? extends D> immediately communicates the upper bound to a developer unfamiliar with A.
According to me you should go with A<? extends D>[] re;
So that user will not allow you to add only object which extends class D
bounded wildcards provides limited flexibility within bound. Any Type with bounded wildcards can only be instantiated within bound and any instantiation outside bound will result in compiler error.One of the important benefit of using bounded wildcard is that it not only restrict number of Type can be passed to any method as argument it also provides access to methods declared by bound. for example TreeMap(Comparator<? super K> comparator) allows access to compare() method of Comparator in Java.
I am coding with Java Generics. I want to define a Binary Tree class generically that will be able to take in any class , and guarantee that that class has the Comparator method compare(T o1, T o2) to see whether I need to follow the right or left subtree for insert into my binary tree.
public class treeDB <T implements Comparator> {
//define my binary tree methods
}
That is my best estimation of how to force to implement Comparator method, but the compile throws an error and I don't know enough to know what it wants.
Everyone has provided the correct syntax, but you might want to consider using Comparable as in
class treeDB <T extends Comparable<T>>
The differences are subtle, and maybe it isn't the better choice. But it never hurts to look.
try this
class treeDB <T extends Comparator<T>> {
...
Firstly, implements should be replaced with extends. In generics extends is the keyword which is used even if the generic type implements an interface.
And secondly, using only Comparator will result in a warning it being a raw type. You must parameterize it. This is your solution:
public class treeDB <T extends Comparator<T>> {
}
This should be public class treeDB <T extends Comparator>, not public class treeDB <T implements Comparator>.
I have a set of classes that all share some common attributes, so I made them all extend a common base class, BaseEntity. So I have, for example Foo extends BaseEntity and Bar extends BaseEntity.
I also want lists of these Foo and Bar objects to be sortable, so I have implemented Comparable. I have the classes defined as Foo extends BaseEntity implements Comparable<Foo> and Bar extends BaseEntity implements Comparable<Bar>, and sorting of lists of Foos or Bars works as expected - and, of course, the details of the sorting are different in the different subclasses. But I can't work out how to make my sorting work when I don't know in advance whether I'll have Foos or Bars. This code, for example, fails to compile:
public class UtilityClass<T extends BaseEntity> {
...bunch of stuff...
List<T> values;
public List<T> sort() {
Collections.sort(values);
return values;
}
...more methods...
}
with the error message Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<T>). The inferred type T is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>
I think the problem is that I am attempting to sort a list of BaseEntity objects, and BaseEntity itself doesn't implement Comparable. But now I face a problem: the only sensible thing to make BaseEntity objects comparable to is other BaseEntity objects, but when I add implements Comparable<BaseEntity> to BaseEntity, the compiler tells me that I've got problems now because my Foo class is trying to implement both Comparable<BaseEntity> and Comparable<Foo>, which evidently is not allowed.
I know I could sidestep this issue by dropping the implements Comparable<Foo> and just implementing Comparable<BaseEntity>, but then my compareTo methods will have to do ugly casting, and I thought that was exactly the sort of problem using generics was supposed to avoid.
What I really want to do is specify in the signature of BaseEntity that all its subclasses will be Comparable, but only to instances of the same subclass.
Any assistance gratefully received. Thanks!
Use an intersection type, like this:
public class MyList<T extends BaseEntity & Comparable<T>> {...}
That specifies that T must be both a BaseEntity and Comparable to itself.
Don't use Collections.sort(List<T>), use Collections.sort(Lst<T>, Comparator<? extends T>) instead. Write the comparation code in the comparator.
Try this:
static <T extends Comparable<? super T>> sort(T[] array);
This is the most general specification to accomplish the task. Basically, it asserts, that T is a type which can be compared to itself.
You could make a super-simple sort method that can handle pretty much any List type
public class Tools {
public static <E> void sortList(List<E> list, Comparator<E> comparator) {
Collections.sort(list, comparator);
}
// Any other utility methods/resources you want in here
}
This means you can call this method to sort any List so long as the given List and Comparator are of the same Type as each other. It would work even without the base class you have (BaseEntity)
I encountered the following piece of a definition for a generic class:
public class binarysearchnode<T extends Comparable<T>> implements Comparable<binarysearchnode<T>>{
.............
}
Please help explaining why a class would specify itself as a Type parameter to comparable while implementing the comparable interface?
How would it be different from the following:
public class binarysearchnode<T extends Comparable<T>> implements Comparable<? super (or extends)T>{
.............
}
This makes it possible to compare binarysearchnodes to each other. If it implemented Comparable<T>, that would instead mean that the node could be compared to the value of the node, which would be odd.
Inside the class you will probably find something like this:
T value;
public int compareTo(binarysearchnode<T> other) {
return value.compareTo(other.value);
}
In order to be able to implement compareTo() like this, the value class (T) needs to be comparable to other objects of its class - hence the declaration of <T extends Comparable<T>> in the class definition.
It is because what the class author wants is to be able to write:
b1.compareTo(b2)
where b1 and b2 are binarysearchnode instances. The developer also adds a constraint to T so that T extends Comparable<T>. Probably so that the implementation of Comparable for binarysearchnode can just rely on T instances being Comparable themselves.
More generally, while it is possible for a class C1 to implement Comparable<C2>, ultimately, it makes no sense to do so: this does not mean that an instance of C2 could be comparable to an instance of C1. And due to type erasure, it would not be possible, for instance, for class C1 to implement both Comparable<C1> and Comparable<C2>.
Also, if binarysearchnode<T> were to implement Comparable<T> directly, you would have at least two problems:
you would not be able to compare one binarysearchnode<T> to another;
given a binarysearchnote<T> instance b and a T instance t, you would be able to write b.compareTo(t) but not t.compareTo(b) (since T does not, and cannot, implement Comparable<binarysearchnode<T>>), and that breaks the Comparable contract.
Let's say you have a superclass A and a subclass B. Imagine the superclass implements Comparable<A>, then B will also implement Comparable<A> through inheritance.
Your binarysearchnode class declared as such :
public class binarysearchnode<T extends Comparable<T>>
will not be able to take B as a type parameter for T (B does not implement Comparable<B>)
But when defined as such :
public class binarysearchnode<T extends Comparable<? super T>>
it will be able to take B as a type parameter for T, since B implements Comparable<A> which fulfills Comparable<? super T>.
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.