如何在ArrayList中找到重复项?< Object>? [英] How to find duplicates in an ArrayList<Object>?

查看:120
本文介绍了如何在ArrayList中找到重复项?< Object>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很常见的问题,但我找不到这个部分:

This is a pretty common question, but I could not find this part:

说我有这个数组列表:

List<MyDataClass> arrayList = new List<MyDataClass>;

MyDataClass{
   String name;
   String age;
}

现在,我需要找到基于 age MyDataClass 中删除​​它们。如何使用像HashSet这样的这里

Now, I need to find duplicates on the basis of age in MyDataClass and remove them. How is it possible using something like HashSet as described here?

我想,我们需要在MyDataClass中覆盖 equals 吗?

I guess, we will need to overwrite equals in MyDataClass?


  1. 但是,如果我没有这样做的奢侈呢?

  2. HashSet如何在内部找到并且不添加重复项?我看到它的实现这里是在OpenJDK ,但无法理解。

  1. But, what if I do not have the luxury of doing that?
  2. And How does HashSet actually internally find and does not add duplicates? I saw it's implementation here in OpenJDK but couldn't understand.


推荐答案

你覆盖两者 equals hashCode HashSet 依赖于两者!)

I'd suggest that you override both equals and hashCode (HashSet relies on both!)

要删除重复项,您只需创建一个新的 HashSet ArrayList作为参数,然后清除ArrayList并放回存储在 HashSet 中的元素。

To remove the duplicates you could simply create a new HashSet with the ArrayList as argument, and then clear the ArrayList and put back the elements stored in the HashSet.

class MyDataClass {
    String name;
    String age;

    @Override
    public int hashCode() {
        return name.hashCode() ^ age.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof MyDataClass))
            return false;

        MyDataClass mdc = (MyDataClass) obj;
        return mdc.name.equals(name) && mdc.age.equals(age);
    }
}

然后执行

List<MyDataClass> arrayList = new ArrayList<MyDataClass>();

Set<MyDataClass> uniqueElements = new HashSet<MyDataClass>(arrayList);
arrayList.clear();
arrayList.addAll(uniqueElements);




但是,如果我没有

然后我建议你做一些装饰师类

Then I'd suggest you do some sort of decorator-class that does provide these methods.

class MyDataClassDecorator {

    MyDataClass mdc;

    public MyDataClassDecorator(MyDataClass mdc) {
        this.mdc = mdc;
    }

    @Override
    public int hashCode() {
        return mdc.name.hashCode() ^ mdc.age.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof MyDataClassDecorator))
            return false;

        MyDataClassDecorator mdcd = (MyDataClassDecorator) obj;
        return mdcd.mdc.name.equals(mdc.name) && mdcd.mdc.age.equals(mdc.age);
    }
}

这篇关于如何在ArrayList中找到重复项?&lt; Object&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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