如何在不改变equals和hashcode的情况下插入集合 [英] how to insert into set without changing the equals and hashcode

查看:111
本文介绍了如何在不改变equals和hashcode的情况下插入集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个建议。
我有一个 Person 类与字符串firstName和字符串lastName
当我搭售插入与相同的字符串像列表值:
set.add(new person(firstName,lastName))

  new person(firstName,lastName))

该集合不过滤对象和他们仍然在进入。
有没有建议在不重写equales和hashcode函数的情况下创建集合列表?
也许用番石榴或一些常规清单?
感谢,
或。

解决方案

您可以创建 TreeSet 与您自己的比较器进行比较。

  Set< Person> set = new TreeSet< Person>(new Comparator< Person>(){
@Override
public int compare(Person p1,Person p2){
//您自己的比较逻辑
}
});


I'm looking for a suggestion. I have a Person class with String firstName and String lastName When i'm tying to insert the list values with the same String like :

set.add(new Person("firstName","lastName"))

set.add(new Person("firstName","lastName"))

The set doesn`t filter the objects and they still getting in the set. There is any suggestion to create set list without overriding the equales and hashcode functions? Maybe with guava or some groovy list? Thanks, Or.

解决方案

You can create a TreeSet with your own Comparator.

Set<Person> set = new TreeSet<Person>(new Comparator<Person>() {
    @Override
    public int compare(Person p1, Person p2) {
        // Your own compare logic
    }
});

这篇关于如何在不改变equals和hashcode的情况下插入集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆