Java 故障排除以实现compareTo方法
我有一门课叫结对:Java 故障排除以实现compareTo方法,java,Java,我有一门课叫结对: public class Pair<K,V> implements Map.Entry<K,V> , Comparable<Pair<K,V>>{ private K key; private V value; public Pair(){} public Pair(K _key, V _value){ key = _key; value = _value;
public class Pair<K,V> implements Map.Entry<K,V> , Comparable<Pair<K,V>>{
private K key;
private V value;
public Pair(){}
public Pair(K _key, V _value){
key = _key;
value = _value;
}
//---Map.Entry interface methods implementation
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V _value) {
return value = _value;
}
///---Map.Entry interface methods implementation
@Override
// if return value negative passed value is bigger
// if return value positive passed value is smaller
// if return value is zero values is equal
public int compareTo(Pair<K, V> o) {
V val1 = o.getValue();
V val2 = this.getValue();
// how to make compare between values(to check if val1 is bigger or equal to val2 and vice versa )
}
}
公共类对实现Map.Entry,可比较{
私钥;
私人价值;
公共对(){}
公共对(K_密钥,V_值){
键=_键;
值=_值;
}
//---Map.Entry接口方法实现
@凌驾
公共K getKey(){
返回键;
}
@凌驾
public V getValue(){
返回值;
}
@凌驾
公共V设置值(V_值){
返回值=_值;
}
///---Map.Entry接口方法实现
@凌驾
//如果返回值为负,则传递的值更大
//如果返回值为正,则传递的值较小
//如果返回值为零,则值相等
公共整数比较(o对){
V val1=o.getValue();
V val2=this.getValue();
//如何在值之间进行比较(检查val1是否大于或等于val2,反之亦然)
}
}
正如您所看到的,类Pair
包含Key
和Value
属性。我需要比较Value属性,并根据比较结果返回int值
在课堂上,我试图实现compareTo
方法,但我不知道如何比较泛型值
如何在compare to方法中实现值的比较?您可以使用
compareTo
的V
,只要V
实现Comparable
接口,依赖于将用作对的值的classe的比较:
public int compareTo(Pair<K, V> o) {
V val1 = o.getValue();
V val2 = this.getValue();
return val1.compareTo(val2);
}
public int compareTo(对o){
V val1=o.getValue();
V val2=this.getValue();
返回val1.compareTo(val2);
}
能够比较V
,
它需要具有可比性。
更改Pair
的声明,使之成为V
上的附加约束,如下所示:
class Pair<K, V extends Comparable<V>> implements Map.Entry<K, V>, Comparable<Pair<K, V>> {
public int compareTo(Pair<K, V> o) {
V val1 = o.getValue();
V val2 = this.getValue();
return val1.compareTo(val2);
}
再解释一下。。。在这个声明中,我们对t
一无所知:
class Item<T> {
class Item<T extends Comparable<T>> {
这里我们知道,T
扩展了compariable
,
因此,此类中T
类型的值具有可比的方法,
这是《代码》与《其他人》的比较
Janos,谢谢你的帖子。你能简要解释一下这一行吗?我只是不明白为什么它会起作用。@Michael我添加了更多的解释,我希望它能帮助Hanks解释。因为我理解这一行“T扩展可比”使T可比!或者只是检查T是否具有可比性?@Michael它没有“检查”。它要求这样做。编译器不允许您为T
使用不可比较的值。确定。。。例如,如果我的T是值类型int,我会得到错误?