首页 > 解决方案 > 无法确定唯一的对象集

问题描述

我正在重写 equals 和 hashcode 方法来定义对象的唯一性,但它似乎不起作用。下面是覆盖等于和哈希码的代码,但它不起作用。还有哪些其他方法可以删除重复项?

public class Test {

    private static class Model {

        private String firstName;
        private String lastName;

        public Model(final String firstName, final String lastName){
            this.firstName = firstName.trim();
            this.lastName = lastName.trim();
        }


        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        @Override
        public String toString() {
            return MoreObjects.toStringHelper(this).add("firstName", firstName).add("lastName", lastName).toString();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Model model = (Model) o;
            return firstName.equalsIgnoreCase(model.firstName) &&
                    lastName.equalsIgnoreCase(model.lastName);
        }

        @Override
        public int hashCode() {
            return Objects.hash(firstName, lastName);
        }
    }

    public static void main(String[] args){

        final List<Model> listWithDuplicates = new ArrayList<>();
        listWithDuplicates.add(new Model("a","b"));
        listWithDuplicates.add(new Model("A","b"));
        listWithDuplicates.add(new Model("a","B "));
        listWithDuplicates.add(new Model("A","B"));

        System.out.println(new HashSet<Model>(listWithDuplicates));

    }
}

预期:[Model{firstName=a, lastName=b} 实际:[Model{firstName=a, lastName=b}, Model{firstName=A, lastName=b}, Model{firstName=a, lastName=B}, Model {名=A,姓=B}]

标签: javaset

解决方案


equalsIgnoreCase您已经测试了与和不与的相等性equals

return firstName.equalsIgnoreCase(model.firstName) &&
       lastName.equalsIgnoreCase(model.lastName);

考虑到用于表示字符串的确切大小写,而在hashCodeandfirstName中进行哈希处理。lastName

为了使其不区分大小写,请将您hasdCode的设置为全部小写或大写:

@Override
public int hashCode() {
       firstName = firstName != null ? firstName.toLowerCase() : firstName;
       lastName = lastName != null ? lastName.toLowerCase() : lastName;
       return Objects.hash(firstName, lastName);
}

推荐阅读