CompareTo method not working - java

I am implementing a Binary Search Tree using BinaryNode to store the data. I am using a CompareTo method in my add and contains methods to determine which sub tree the item belongs in. I keep getting this error various places where compare is used:
BST.java:50: error: cannot find symbol
if (item.CompareTo(root.data) > 0)
^
symbol: method CompareTo(T)
location: variable item of type T
where T is a type-variable:
T extends Comparable<? super T> declared in class BST
Here is my code, what am I doing wrong?
import java.util.List;
import java.util.ArrayList;
import java.util.*;
import java.io.*;
public class BST<T extends Comparable<? super T>> implements BSTInterface<T>
{
private BinaryNode<T> root;
private int numberOfItems;
public List<T> preOrder = new ArrayList<T>();
public List<T> inOrder = new ArrayList<T>();
public List<T> postOrder = new ArrayList<T>();
public BST()
{
root = null;
numberOfItems = 0;
}
public BST(T rootData)
{
root = new BinaryNode<T>(rootData);
numberOfItems = 1;
}
public BST(T rootData, BST<T> leftTree, BST<T> rightTree)
{
root = new BinaryNode<T>(rootData);
numberOfItems = 1;
root.left = leftTree.root;
root.right = rightTree.root;
}
public void setTree(T rootData)
{
root = new BinaryNode<T>(rootData);
}
public boolean contains(T item)
{
if (root.data.equals(item))
return true;
else
{
if (item.CompareTo(root.data) > 0)
{
root = root.left;
return contains(item);
}
else if (item.CompareTo(root.data) < 0)
{
root = root.right;
return contains(item);
}
else
return false;
}
}
public void add(T newItem)
{
if (root == null)
{
root = new BinaryNode<T>(newItem);
numberOfItems++;
}
if (newItem.equals(root.data))
return;
if (newItem.CompareTo(root.data) < 0)
{
root = root.left;
add(newItem);
}
if (newItem.CompareTo(root.data) > 0)
{
root = root.right;
add(newItem);
}
}

This isn't c# :p
item.CompareTo()
change to:
item.compareTo()
compareTo is coming from the Comparable interface.

[Comparable<T>][1] has following signature
int compareTo(T o)
Compares this object with the specified object for order.
But you are using CompareTo() Please correct the case and than try

Its compareTo() not CompareTo() // you are using capital C which is wrong
int java.lang.Comparable.compareTo(? super T o):-
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
Parameters:
o - the object to be compared.
Returns:
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Throws:
ClassCastException - if the specified object's type prevents it from being compared to this object.

If you are implementing java.lang.Comparable, then the method should be called compareTo(), not CompareTo().
To avoid this type of error, it is advisable to use the #Override annotation in front of your methods. This way Eclipse will tell you that you are not overriding an existing method.

Related

How to define a generic comparable array class?

I want to define a generic class ComparableList<> that extend ArrayList and implements Comparable interfaces, such that two objects of type ComparableList can be compared using the compareTo method. The compareTo should perform a lexicographic comparison.
Here's my code:
class ComparableList <T extends Comparable<T>> extends ArrayList implements Comparable<ComparableList>{
#Override
public int compareTo(ComparableList o){
Iterator citer = this.iterator();
Iterator oiter = o.iterator();
while (citer.hasNext() && oiter.hasNext()){
if (citer.next() > oiter.next()){
return 1;
}else if (citer.next() < oiter.next()){
return -1;
}else {
if (!citer.hasNext()){
return -1;
}
if(!oiter.hasNext()){
return 1;
}
}
}
return 0;
}
}
and I got error messages like this:
TCL.java:11: error: bad operand types for binary operator '>'
if (citer.next() > oiter.next()){
^
first type: Object
second type: Object
TCL.java:13: error: bad operand types for binary operator '<'
}else if (citer.next() < oiter.next()){
^
first type: Object
second type: Object
I thought it should be a ComparableList but not an Object. Can anyone tell me the reason?
You need to compare the objects using Comparable.comapreTo() (that's why you have <T extends Comparable<T> there). You need to first check for nulls on either side.
Also, each call to Iterator.next() iterates to next element, you don't want to call it twice in one loop iteration - store the items at the loop start then use the stored values.
Comparable doesn't override the > and < operators (nothing can). Since your T implements Comparable, use compareTo:
int result = citer.next().compareTo(oiter.next());
if (result != 0) {
return result;
} else {
if (citer.hasNext()) {
return -1;
}
if (oiter.hasNext()) {
return 1;
}
}
Note that that also calls next only once per iteration, since next advanced the iterator.
Each element in your ComparableList is of type T extends Comparable<T>, for sure the binary operator is not available for it (Java doesn't have operator overloading), but since it extends Comparable, you have compareTo to be used as replacement for < and >. Use it instead.

comparing two generic objects if the one is "greater" or "smaller"

I want to generate a binary tree with key - value pairs in their nodes.
In my binary tree I want to implement nodes at the beginning with an insert method, which implements a new left node if the key is smaller than the key of the current node. Then if there is already a left node it will check again for it. The same logic follows for right/greater node inserts.
I wrote my code first using the int type because it's way easier for me to test my code before I use generics (new topic for me). It worked when using int but I an unsure how to compare two generics with themselves by using "<" or ">".
public ListCell<Type> checkKey(Type key, ListCell<Type> checkCell) {
ListCell<Type> newCell = null;
if (key < checkCell.key && checkCell.left != null) {
...
}
...
}
I don't know if it's worth saying but I'm creating my binary tree with a selfcoded list.
Above you can see my current checks but i can't compare my given key now with checkCell.key because of them not being numbers.
So my general question is how to compare the keys in generics if they are "smaller" or "greater" than the other for my implementation in a binary tree.
Thanks in advance
You would need to ensure that your generic type implemented the Comparable interface, and then use the compareTo method instead. Java does not support overloading the > operator (or any operator overloading, for that matter).
As per the documents, compareTo:
Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
An example (that you'll have to map on to your exact code), assuming that key is your item you will store in your node, and checkCell.key is your node
int compareResult = key.compareTo(checkCell.key);
if (key < 0) { // it goes on the left }
else if (key == 0) { // it is the same }
else { // it goes on the right }
In your compareTo method you need to decide what fields in your class determine it's "ordering". For example, if you have a size and priority field, you might do:
#Override public int compareTo(Type other) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == other) return EQUAL;
if (this.size < other.size) return BEFORE;
else if (this.size > other.size) return AFTER;
else { // size is equal, so test priority
if (this.priority < other.priority) return BEFORE;
else if (this.priority > other.priority) return AFTER;
}
return EQUAL;
}
Bounded type parameters are key to the implementation of generic algorithms. Consider the following method that counts the number of elements in an array T[] that are greater than a specified element elem.
public static <T> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e > elem) // compiler error
++count;
return count;
}
The implementation of the method is straightforward, but it does not compile because the greater than operator (>) applies only to primitive types such as short, int, double, long, float, byte, and char. You cannot use the > operator to compare objects. To fix the problem, use a type parameter bounded by the Comparable<T> interface:
public interface Comparable<T> {
public int compareTo(T o);
}
The resulting code will be:
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
bounded type parameters

Eclipse type mismatch errors on same wildcard

I'm doing an assignment that requires me to implement skip lists and binary search trees. I'm also supposed to implement iterators for each data structure.
The skip list and binary search tree is implemented using generics K and V.
public class SkiplistMap<K extends Comparable<K>,V> implements SortedMap<K,V>
public class SkiplistMapNode<K extends Comparable<K>,V>
public class BSTMap<K extends Comparable<K>,V> implements SortedMap<K,V>
public class BSTMapNode<K extends Comparable<K>,V>
The iterators only use the comparable type, so I plugged in ? as the non comparable type.
public class SkiplistMapIterator<T extends Comparable<T>> implements Iterator<T> {
SkiplistMap<T,?> list;
Queue<SkiplistMapNode<T,?>> queue;
int version;
public SkiplistMapIterator(SkiplistMap<T,?> sl){
list = sl;
queue = new LinkedList<SkiplistMapNode<T,?>>();
SkiplistMapNode<T,?> N = sl.getHead();
while (N != null){
queue.add(N);
N = N.getNext()[0];
}
version = sl.getVersion();
}
public void remove() throws UnsupportedOperationException{
if (queue.isEmpty()) throw new UnsupportedOperationException("No element present");
else {
T toRemove = queue.remove().getKey();
SkiplistMapNode<T,?> N = list.getHead();
while (N != null){
if (N.getNext()[0].getKey().compareTo(toRemove) == 0){
SkiplistMapNode<T,?> found = N.getNext()[0];
for (int l = list.getLevel()-1; l >= 0; l--){
N.getNext()[l] = N.getNext()[l].getNext()[l];
found.getNext()[l] = null;
}
list.incVersion();
break;
}
N = N.getNext()[0];
}
}
}
}
My problem: correctness of the code aside, when I try to make two SkiplistMap or SkiplistMapNode objects point to each other, Eclipse freaks out screaming there's a type mismatch. It tells me
Type mismatch: cannot convert from SkiplistMapNode<T,capture#16-of ?> to SkiplistMapNode<T,capture#15-of ?>
But I'm typing in the same question mark, so I'm not sure why Eclipse hates it. Can anyone explain it in dummy terms? I've tried "typing" the method but it's giving me even more errors.
1. It's not guaranteed that two ? wildcards are the same type. If it was, the ? would be a nonsense, because that's why they are: for representing an unknown type.
2. Look at the types that should be converted. 'Capture#15 of ...' and 'Capture#16 of ...' seem to be two different things.
How many question marks do you think there are in java?
Every occurrence represents an unknown type, so the compiler has to assume they are all different.
Give your "don't care" type a name, even if it has no constraints.

What is the best way to get min and max value from a list of Comparables that main contain null values?

I am thinking about something like this:
public static <T extends Comparable<T>> T minOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.first();
}
public static <T extends Comparable<T>> T maxOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.last();
}
But is not null safe, which is something I want too.
Do you know a better way to solve this problem?
EDIT:
After the comments I have also tried min():
public static <T extends Comparable<T>> T minOf(T...ts){
return Collections.min(Arrays.asList(ts), new Comparator<T>(){
public int compare(T o1, T o2) {
if(o1!=null && o2!=null){
return o1.compareTo(o2);
}else if(o1!=null){
return 1;
}else{
return -1;
}
}});
}
What do you think of that?
What's wrong with Collections.max?
And why do you care about null safety? Are you sure you want to allow nulls to be in your Collection?
If you really need to exclude "null" from the result, and you can't prevent it from being in your array, then maybe you should just iterate through the array with a simple loop and keep track of the "min" and "max" in separate variables. You can still use the "compare()" method on each object to compare it with your current "min" and "max" values. This way, you can add your own code for checking for nulls and ignoring them.
EDIT: here's some code to illustrate what I'm talking about. Unfortunately there is an edge case you need to consider - what if all of the arguments passed in are null? What does your method return?
public static <T extends Comparable<T>> T minOf(T...ts){
T min = null;
for (T t : ts) {
if (t != null && (min == null || t.compareTo(min) < 0)) {
min = t;
}
}
return min;
}
public static <T extends Comparable<T>> T maxOf(T...ts){
T max = null;
for (T t : ts) {
if (t != null && (max == null || t.compareTo(max) > 0)) {
max = t;
}
}
return max;
}
You should not implement Comparable to accept null, as it breaks the interface's contract.
From https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html :
Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
You must instead create a new interface, e.g. ComparableNull instead.
See also:
What should int compareTo() return when the parameter string is null?
How to simplify a null-safe compareTo() implementation?

Java Generics and Infinity (Comparable)

With the type Integer you can do this:
int lowest = Integer.MIN_VALUE;
What can I do if I use generics?
K lowest = <...>;
I need this in order to implement something similar to a PriorityQueue.
I have access to a node I want to remove from the queue, but it is not the min.
1. I need to make it the min by decreasing the key of that node,
2. And then remove the min.
I am stuck on the first step. The only thing I can do is set the key of the node to the current min. Not sure it is enough.
There is no generic form of MIN_VALUE or MAX_VALUE for all Comparable types.
Think about a Time class that implements comparable. There is no MAX_VALUE for Time even though it is Comparable.
I am trying to imagine what scenario would require such behavior. This is the best I can come up with...
WARNING: This code is dangerous. Please be merciful to me for posting such an abomination. It is only a proof of concept.
public class Lowest<K> implements Comparable<K> {
public int compareTo(K other) {
return -1;
}
}
And then...
public class Test {
public <K extends Comparable<K>> K findMaximum(List<K> values) throws Exception {
K lowest = (K) new Lowest<K>(); /// XXX DANGER! Losing compile-time safety!!!
K maximum = lowest;
for (K value : values) {
if (maximum.compareTo(value) < 0) {
maximum = value;
}
}
if (maximum == lowest) {
throw new Exception("Could not find a maximum value");
} else {
return maximum;
}
}
}
This doesn't make any sense...
Given that you don't know what K is at that point, (i.e. You're implementing it generically... duh!) you can't specify a min/max bound for it.
in a case where K could be a int, long, string OR object, you couldn't sensibly guess to use
Integer.MIN_VALUE, "" OR NULL.
I guess what you're looking for is a K.MIN_VALUE_OF_EVENTUAL_TYPE but that doesn't exist.
You can make a wrapper class that "adds" a minimum and maximum value to all types. It just has two static instances that represent minimum and maximum, and then other instances wrap some other value of some type. When we do a comparison, we check if one of the things is the minimum or maximum, and return the proper result; and otherwise we just do the same comparison as the underlying type. Something like this:
class Extended<T extends Comparable<? super T>> implements Comparable<Extended<T>> {
private Extended() { }
private static Extended min = new Extended();
private static Extended max = new Extended();
#SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> Extended<T> getMin() {
return (Extended<T>)min;
}
#SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> Extended<T> getMax() {
return (Extended<T>)max;
}
public T value;
public Extended(T x) { value = x; }
public int compareTo(Extended<T> other) {
if (this == other) return 0;
else if (this == min || other == max) return -1;
else if (this == max || other == min) return 1;
else return this.value.compareTo(other.value);
}
}
Consider not making K a generic, but using an interface that wraps the primitive wrapper (a double wrapper!).
import java.util.HashMap;
public class NodeWrapper<K extends Comparable<K>> implements Comparable<NodeWrapper<K>> {
private static HashMap<Class, NodeWrapper> minVals = new HashMap<Class, NodeWrapper>();
private K value;
private NodeWrapper() {
super();
}
public NodeWrapper(K value, Class<K> clazz) {
super();
this.value = value;
if (minVals.get(clazz)==null) {
minVals.put(clazz, new NodeWrapper<K>());
}
}
public K getValue() {
return value;
}
public static NodeWrapper getMinValue(Class clazz){
return minVals.get(clazz);
}
public void setValue(K value) {
this.value = value;
}
#Override
public int compareTo(NodeWrapper<K> o) {
NodeWrapper min = minVals.get(this.getClass());
if (this==min && o==min) {
return 0;
} else if (this==min){
return -1;
} else if (o==min){
return 1;
} else {
return this.value.compareTo(o.value);
}
}
}
Briefly, the idea is that whenever a new class is instantiated, a minimum value is created and put into a static hashmap that stores the minimum values for each class. (In fact, these values are NOTHING at all, just a sentinel object, but since we will use object equality to determine if something is the min value, this is no problem at all.) All that's necessary is that the wrapped object be comparable to other instances of itself in general.
One drawback is that when you call getMinValue you will have compiler warnings, since the return type will have no generic information. There may be a more elegant way around this, but I can't think of it right now.
This general idea might be rather nice overall. However, I should really stress: this will absolutely break if you try it with any polymorphism or any mixing of mutually comparable classes. Longs and Integers in the same tree will completely destroy you.
er... what's the problem again?
PriorityQueue, like all Collections, allows you to use an instance of an object to remove it from the collection.
Uh doesn't this depend on what type K is?
The point of Generics is that K can be any type (or any subclass of a certain type); in order to be able to call methods on K or access properties of it, you need to restrict it's type bounds with wildcards.
just because an object is a comparable does not mean it has to have a minimum value. The reason int has a min value of -(2^(31)) is because you need 1 bit for a sign, so 2^31 is the largest (or smallest) possible integer that can be stored. For things like string, it does not make any sense since there is no largest/smallest possible string, it is memory bound.
You might have to create an interface "IInfinity", and have K extends IInfinity, and IInfinity to have a method "getInfinityValue()", and then wrap/extend Integer, Double, BigDecimal, etc in a class that implements IInfinity ... and ugh!
Basically you want any type K to implement some static functions say lowest and highest which obey the standard mathematical properties.
I assume that for this sense of lowest (or highest) to be usable you would want any Comparable object to have these methods. (or static fields). If you are only interested in your own custom objects, the way to do this would be to have everything inherit from an abstract data type which declared static fields for MINVALUE and MAX_VALUE and then your type varaibles would be . If you need this functionality for other classes you will need to cre4ate some sort of external hashmap which tracks these properties for different classes (but that would get pretty ugly)

Categories