在TreeSet和TreeMap中使用hashCode()和equals()

问题描述 投票:5回答:1

从以下代码中,我了解到,不需要为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的图片中?我可以获得代码示例吗?谢谢!

java treemap treeset
1个回答
11
投票

你刚才说:

TreeSet实例使用compareTo(或compare)方法执行所有元素比较

equals()hashCode交易时,TreeSetTreeMap没有进入画面。但是,如果您将来使用此对象作为HashMap(例如)的键,则最好正确覆盖它们。

© www.soinside.com 2019 - 2024. All rights reserved.