无法确定唯一的对象集

时间:2019-04-25 06:01:32

标签: java set

我正在重写equals和hashcode方法来定义对象的唯一性,但是它似乎不起作用。 以下是重写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 {firstName = A,lastName = B}]

1 个答案:

答案 0 :(得分:0)

您已经用equalsIgnoreCase而不是equals测试了相等性:

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

hashCodefirstName中对lastNamehasdCode进行哈希处理时要考虑到用于表示字符串的确切大小写。

要使其不区分大小写,请将@Override public int hashCode() { firstName = firstName != null ? firstName.toLowerCase() : firstName; lastName = lastName != null ? lastName.toLowerCase() : lastName; return Objects.hash(firstName, lastName); } 设置为小写或大写:

session_set_cookie_params(86400, '/', '', false, false);
setcookie('gdpr_privacy_bar', 1, time()+31556926, '/', $_SERVER['SERVER_NAME]);