从以下代码中,我了解到,不需要为TreeSet和TreeMap重写equals()和hashCode()方法,既不需要排序也不需要搜索。
public class ComparableTest implements Comparable<ComparableTest> {
private String username;
public ComparableTest(String name) {
this.username = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int compareTo(ComparableTest o) {
return username.compareTo(o.getUsername());
}
@Override
public String toString() {
return this.getUsername();
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
ArrayList<ComparableTest> comparableTestsList = new ArrayList<ComparableTest>();
ArrayList<ComparableTest> comparableTestsList2;
comparableTestsList.add(new ComparableTest("Second Name"));
comparableTestsList.add(new ComparableTest("First name"));
System.out.println("Orignal Array List = " + comparableTestsList);
// making a clone to test this list in Treeset
comparableTestsList2 = (ArrayList<ComparableTest>) comparableTestsList
.clone();
// Sorting the first arraylist which works
Collections.sort(comparableTestsList);
System.out.println("Sorted Array List = " + comparableTestsList);
// searching the first array which does not work as equals method has
// not been overriden
int position = comparableTestsList.indexOf(new ComparableTest(
"First name"));
System.out.println("The position of First name is = " + position);
//using the cloned collection in TreeSet
TreeSet<ComparableTest> ts = new TreeSet<ComparableTest>(
comparableTestsList2);
System.out.println("The value in Tree Set is = " + ts);
System.out.println("The position of First name is = " + ts.contains(new ComparableTest("First name")));//works fine
//using the cloned collection in TreeMap
TreeMap<ComparableTest, String> tMap = new TreeMap<>();
for(ComparableTest ct: comparableTestsList2) {
tMap.put(ct, "anushree");
}
System.out.println("The value in Tree Map is = " + tMap);
System.out.println(tMap.get(new ComparableTest("First name")));//works fine
}
}
这与javadoc http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html中的内容非常吻合 TreeSet实例使用compareTo(或compare)方法执行所有元素比较,因此从集合的角度来看,这个方法认为相等的两个元素是相等的。集合的行为即使其排序与equals不一致也是明确定义的;它只是没有遵守Set接口的一般合同。
还写了: 请注意,如果要正确实现Set接口,则由set维护的排序(无论是否提供显式比较器)必须与equals一致。
如何将equals()和hashCode()用于TreeSet和TreeMap的图片?我可以获得代码示例吗?谢谢!
答案 0 :(得分:11)
你刚才说:
在TreeSet实例使用compareTo(或compare)方法
执行所有元素比较
equals()
和hashCode
进行交易时, TreeSet
和TreeMap
不会出现。但是,如果您将来使用此对象作为HashMap
的键(例如),则最好正确覆盖它们。
答案 1 :(得分:0)
同意您@Tunaki的输入。 TreeSet和TreeMap不需要hashCode和equals方法,因为排序取决于客户端提供的compareTo或compare方法。我认为这就是为什么这两个DS的containsKey方法和TreeMap的get(key)方法都在log(n)时间而不是O(1)时间运行的原因,因为它们不是像HashMap或HashTable这样基于哈希的数据结构通过在键上应用哈希函数可以在O(1)时间内找到元素的位置。对于TreeSet和TreeMap,将应用二进制搜索来定位元素。