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

Anu*_*jee 5 java treemap treeset

从以下代码中,我了解到,不需要为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
    }
}
Run Code Online (Sandbox Code Playgroud)

这与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的图片中?我可以获得代码示例吗?谢谢!

Tun*_*aki 12

你刚才说:

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

equals()hashCode打交道时,当进不来的图片TreeSetTreeMap.但是,如果您将此对象用作HashMap(例如)将来的密钥,则最好正确覆盖它们.