Java 绑定与存储实现可比较的通用对象的通用arraylist不匹配
我的老师说,一旦我在入门课上实现了comparable,边界不匹配错误就会消失 这将生成错误:Java 绑定与存储实现可比较的通用对象的通用arraylist不匹配,java,generics,Java,Generics,我的老师说,一旦我在入门课上实现了comparable,边界不匹配错误就会消失 这将生成错误: public class BucketList<V> implements BucketListADT<V> { //The Error underline under 'Entry' should clear once you make the //Entry object properly comparable. See Entry.java pr
public class BucketList<V> implements BucketListADT<V> {
//The Error underline under 'Entry' should clear once you make the
//Entry object properly comparable. See Entry.java
private ArrayList<MySortedArray<Entry<V>>> list;
private int min;
private int max;
public类BucketList实现BucketListADT{
//一旦您进行了更改,“Entry”下的错误下划线应清除
//Entry对象具有适当的可比性。请参阅Entry.java
私有数组列表;
私用int min;
私人int max;
下面是我的入门类,需要实现:
public class Entry <V extends Comparable<V>> {
private int key;
private V val;
public Entry(int k, V v) {
key = k;
val = v;
}
public int getKey() {
return this.key;
}
public V getValue() {
return this.val;
}
public String toString() {
return this.getValue()+"="+this.getKey();
}
public int compareTo(int key2){
if(key > key2) return 1;
if(key < key2) return -1;
else return 0;
}
}
公共类条目{
私钥;
私人诉瓦尔;
公共入口(int k,V){
key=k;
val=v;
}
public int getKey(){
返回此.key;
}
public V getValue(){
返回此.val;
}
公共字符串toString(){
返回this.getValue()+“=”+this.getKey();
}
公共整数比较(整数键2){
如果(键>键2)返回1;
如果(键<键2)返回-1;
否则返回0;
}
}
在
条目
类声明中,它是否应该是
之外的东西?了解更多关于您得到的错误的信息将非常有用。到目前为止,我可以告诉您的是,您的条目类没有实现Comparable。您用该代码说的是V实现Comparable。也许您希望,m可能不是。要让代码的其余部分知道条目实现了可比性,您应该编写:
公共类条目实现可比较的{…
也就是说,如果您希望V也具有可比性。在这种情况下,您还应该像在BucketList中那样指定它,否则BucketList会说它可能有任何V,即使它不具有可比性,但在使用它之后,就好像它保证具有可比性一样。如果您不希望V必须实现可比性,只需更改
public class Entry <V extends Comparable<V>> implements Comparable<Entry<V>> {
private int key;
private V val;
public Entry(int k, V v) {
key = k;
val = v;
}
public int getKey() {
return this.key;
}
public V getValue() {
return this.val;
}
public String toString() {
return this.getValue()+"="+this.getKey();
}
public int compareTo(Entry entry){
if(key > entry.key) return 1;
if(key < entry.key) return -1;
else return 0;
}
}
公共类条目实现了可比较的{
私钥;
私人诉瓦尔;
公共入口(int k,V){
key=k;
val=v;
}
public int getKey(){
返回此.key;
}
public V getValue(){
返回此.val;
}
公共字符串toString(){
返回this.getValue()+“=”+this.getKey();
}
公共整数比较(条目){
if(key>entry.key)返回1;
if(key
是的,我希望Entry实现Comparable,而不是现在我意识到的扩展它。我应该比较键值。