takesuma :
I run into a problem that I do not understand. In the method of adding in the Table class I would like to use:
Arrays.binarySearch(asso, (a,b) -> a.cle.compareTo(b.cle));
Where asso is my array of Association objects containing the key and the value.
By executing this code with the type String, I get an error "cannot find symbol" on the method compareTo(Object).
There my code:
test:
Table<String,String> table0 = new Table<String,String>(10);
table0.add("1","int");
method:
import java.util.Arrays;
public class Table<C,V>{
Association[] asso;
public Table(int n){
asso = new Association[n];
}
public void add(C cle, V valeur){
asso[0] = new Association<C,V>(cle,valeur);
Arrays.sort(asso, (a,b) -> a.cle.compareTo(b.cle));
}
public class Association<C,V>{
public C cle;
public V valeur;
public Association(C cle,V valeur){
this.cle = cle;
this.valeur = valeur;
}
}
}
And the error:
../src/Table.java:15: error: cannot find symbol
Arrays.sort(asso, (a,b) -> a.cle.compareTo(b.cle));
^
symbol: method compareTo(Object)
location: variable cle of type C
where C is a type-variable:
C extends Object declared in class Table.Association
Thank you for your help.
Eran :
Add a type bound to the generic type parameter C
:
class Table<C extends Comparable<C>,V>
Otherwise the compiler doesn't know that C
implements Comparable
(and therefore must have the compareTo
method).
Also don't use raw type (Association[]
) for the array. Use:
Association<C,V>[] asso;
On second thought, I also suggest you make the Association
class static
:
public class Table<C extends Comparable<C>,V> {
Association<C,V>[] asso;
public Table(int n) {
asso = new Association[n];
}
public void add(C cle, V valeur) {
asso[0] = new Association<C,V>(cle,valeur);
Arrays.sort(asso, (a,b) -> a.cle.compareTo(b.cle));
}
public static class Association<C,V> {
public C cle;
public V valeur;
public Association(C cle,V valeur){
this.cle = cle;
this.valeur = valeur;
}
}
}