I've run into a headache I'm having difficulty debugging. I am trying to compare two generic values so I can insertion sort them according to values into an array. This is my first time working with the Comparable and Comparator interfaces so any additional advice surrounding these issues would be great.
This is how my class is set up:
public class SVStore<K, V extends Comparable<V>> implements Pairs<K, V>, Iterable<K>, Comparable<V>, Comparator<V> {
The put() method:
@Override
public V put(K key, V value) {
SVData<K, V> tab[] = table;
for (int i = 0; i < table.length - 1; i++) {
if (value.compareTo(tab[i].dataValue) <= 0) {
int index = i;
for( int j = index; j < size - 1; j++){
tab[j + 1] = tab[j];
}
}
tab[i].setDataKey(key);
tab[i].setDataValue(value);
size++;
}
return value;
}
These are the compareTo() and compare methods I am trying to implement.
@Override
public int compareTo(V t) {
return compare(t, this);
}
@Override
public int compare(V t, V t1) {
if (t.equals(t1)){
return 0;
} else if (t < t1){
return -1;
} else {
return 1;
}
}
The first issue I am running into is in the compareTo() method and it is centering around "this". The error says "required: V,V found: V,SVStore". I know the answer is not to cast "this" to V. How do I compare it to the V in that array index?
The second issue I am having is... } else if (t < t1){ in the compareTo() method. The error is "bad operand types for binary operator '<' first type: V second type: V". If it is recognizing both as V for both types why is it a bad operand?
I think all the code needed is there. I try to keep these as concise as possible, but if there's any additional code someone needs, I'm happy to provide it. Cheers!
Thanks to the combined efforts of Chrylis, Catalin Pol, and Louis Wasserman, I learned I needed to correct my class to:
I no longer needed to write my own compareTo() method.
This did the trick. I'm relatively new to java so it took me a while to get what everyone was saying, but everyone was persistent with their efforts. Thanks to all for the help!