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>.
Related
I tried commenting on the thread below itself, but I do not have enough rep points for it.
My simple question is: what is difference between the following two codes?
Please note: I am not sure if the former is even valid syntax, and maybe that's the answer.
public class BinarySearchTree<T> extends Comparable<T> {}
public class BinarySearchTree<T extends Comparable<T>> {}
Java : How do I implement a generic Binary Search Tree?
public class BinarySearchTree<T> extends Comparable<T> {}
The tree is Comparable and can hold any type. Tree objects would be compared by the type they hold. Maybe you are comparing only the root elements of the trees? This is not valid because Comparable is an interface; you cannot extend classes from interfaces.
public class BinarySearchTree<T extends Comparable<T>> {}
The tree can only contain Comparable types. This is valid.
You could combine the two into the following:
public class BinarySearchTree<T extends Comparable<T>> implements Comparable<BinaryTree<T>> {}
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>.
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.
I wanted to do something along the lines of:
public class MyClass<T implements Comparable> {
....
}
But I can't, since, apparently, generics only accept restrictions with subclasses, and not interfaces.
It's important that I'm able to compare the types inside the class, so how should I go about doing this? Ideally I'd be able to keep the type safety of Generics and not have to convert the T's to Object as well, or just not write a lot of code overall. In other words, the simplest the better.
The implements is wrong. It only accepts extends or super. You can use here extends:
public class MyClass<T extends Comparable<T>> {
// ...
}
To learn more about Generics, you may find this tutorial (PDF) useful.
The best way to do it is:
public class MyClass<T extends Comparable<? super T>> {
....
}
If you just do <T extends Comparable<T>>, then it won't work for subclasses of comparable classes.
Also for interfaces you have to use extends. So in your case it would be:
public class MyClass<T extends Comparable<T>> {
....
}