I am having trouble implementing a compareTo() method.
I am creating an ArrayedHeap that stores items of type I, where I is later defined.
For example ArrayedHeap<Integer> H = new ArrayedHeap280<Integer>(10); // 10 is simply the capacity
What I fail to comprehend is that when I am creating the compareTo(I item) method I dont know what I is, seeing as it is later defined.
So how I can I implement a compareTo method when I cant use operators such as < and > or <= and >=?
When I try what I have below, eclipse tells me "The operator > is undefined for the argument type(s)
Welcome to the Ranch. Please UseCodeTags when you post source code.
So, you're creating a class that has a type parameter I, and now you want to do something with those I objects in your compareTo() method.
If you define your class like this:
then inside your class, you can't do much with objects of type I, because anything could be filled in for the I. You certainly can't compare instances of I with operators like >, because the compiler can't check that an operator > actually exists for objects of some unknown type I.
To be able to compare objects of type I, you have to specify constraints for the type parameter I. For example:
What this is expressing is: for I, you can use any type that implements the Comparable interface for I. By doing this, the compiler knows that compareTo() will always be available on I, so you can call it.
Have a look at this example:
Note: You'll never be able to use operators like < and > to compare instances of I; those operators are only defined for numeric primitive types (int, long, float, double, etc.) and cannot be used on objects.
Welcome to the Ranch I have added cpde tags and you can see how much better your post looks.
The Comparable interface says it is for classes with a "natural ordering". It is obvious from the way you have written that the Item class has a "natural ordering". But what about the Heap class? How will that have a "natural ordering"? If you can't give a simple explanation, then maybe the Heap class doesn't have a "natural ordering" at all, and the Item class should implement Comparable<T>, not the Heap class.
By the way, Jesper, isn't it Heap<Comparable<T extends Comparable<? super T>>>? The compareTo method might be declared in a superclass of T.