Chr*_*row 8 java collections hash set comparable
如果一个对象拥有一个唯一的主键,那么它需要实现哪些接口才能实现集合友好,特别是在高效排序,可清洗等方面...?
如果主键是字符串,那么如何最好地实现这些接口?
谢谢!
Eli*_*ght 12
您必须实现equals,hashCode和(在实现Comparable接口之后)compareTo.
在每种情况下,由于您有一个主键字符串,您可以考虑将这些调用分配给您的字符串.例如:
public class Friendly implements Comparable<Friendly>
{
// presumably you've got other fields as well
private String primaryKey;
public Friendly(String primaryKey)
{
this.primaryKey = primaryKey;
}
public int compareTo(Friendly other)
{
return primaryKey.compareTo(other.primaryKey);
}
public int hashCode()
{
return primaryKey.hashCode();
}
public boolean equals(Object o)
{
return (o instanceof Friendly) && primaryKey.equals(((Friendly)o).primaryKey);
}
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*ael 11
你必须覆盖Object.equals()
和Object.hashCode()
,同时也实现了Comparable
接口.这将使您的类在进行任何类型的排序或散列(包括使用Collections.sort(
),任何Map
类或任何Set
类时完全"兼容" .如果甚至有一个微小的机会,类将被放置在某种集合,那么它应该肯定实现所有这三种方法.
public class A implements Comparable<A>{
private String key;
@Override
public boolean equals(Object obj){
if (this == obj) return true;
if (!(obj instanceof A)) return false;
A that = (A)obj;
return this.key.equals(that.key);
}
@Override
public int hashCode(){
return key.hashCode();
}
@Override
public int compareTo(A that){
//returns -1 if "this" object is less than "that" object
//returns 0 if they are equal
//returns 1 if "this" object is greater than "that" object
return this.key.compareTo(that.key);
}
}
Run Code Online (Sandbox Code Playgroud)
请记住,如果两个对象相等,那么:
compareTo()
必须返回0.字符串已经非常适合于散列和比较,因此如果您的对象可以通过字符串真正唯一标识,那么您的状态良好.只需确保实现Comparable
用于排序和覆盖的接口equals
以及hashCode
(委托给主键字符串)进行散列,你就可以了.