2

我正在尝试使用可比较的接口,以便可以在Param<?,?>对象列表上使用 Collection API 中的搜索算法。我不知道如何compareTo正确实现方法,因为它的字段不是必需的数字。如何实现此方法,以便 Collections API 算法与此对象的集合正常工作?

public final class Param <K,V> implements Comparable<Param<K,V>>{

private final K key;
private final V value;

public Param (K key, V value)
{
    this.key = key;
    this.value = value;
}

@Override
public boolean equals(Object obj) 
{
    if(obj == null)
        return false;

    if (!obj.getClass().getName().equals(this.getClass().getName()))
        return false;

    @SuppressWarnings("unchecked")
    Param<K, V> param = (Param<K, V>)obj;
    if (this.getKey ().equals(param.getKey()) && this.getValue().equals(param.getValue()))
        return true;

    return false;
}

@Override
public int hashCode() 
{
    int hash = 5;

    hash += this.key.hashCode();
    hash += this.value.hashCode();
    return hash;
}


public int compareTo(Param <K,V> o)
{
    if (this.hashCode() == o.hashCode())
        return 0;
    return -1;
}
}
4

0 回答 0