如何从ArrayList中删除重复的元素(即myClass对象)?

3

我有一个ArrayList

ArrayList<WorkPosition> info = new ArrayList<>();

有时我会向某个点添加一些对象,最终这个ArrayList会有多个相同的对象。该对象具有一些int值和2个数组列表。

97 [9, 10, 15] [1202, 1204, 2082]
97 [9, 10, 15] [1202, 1204, 2082]
97 [9, 10, 15] [1202, 1204, 2082]
42 [14, 16, 29] [404, 1081, 1201D]
42 [14, 16, 29] [404, 1081, 1201D]
42 [14, 16, 29] [404, 1081, 1201D]
57 [18, 30, 32] [2081, 435, 1032]
57 [18, 30, 32] [2081, 435, 1032]
57 [18, 30, 32] [2081, 435, 1032]
34 [19, 27, 28] [4501, 831, 201]
34 [19, 27, 28] [4501, 831, 201]
34 [19, 27, 28] [4501, 831, 201]

有没有办法删除多余的出现次数?我读了这篇文章如何从ArrayList中删除重复元素?但在我的情况下,我没有Strings,而是对象类型为WorkPosition..

public class WorkPosition {

    private int id;
    ArrayList<Integer> machines = new ArrayList<>();
    ArrayList<String> bottles= new ArrayList<>();


    public WorkPosition(int id, ArrayList<Integer> machines, ArrayList<String> bottles) {

        this.id = id;
        this.machines = machines;
        this.kaloupia = kaloupia;
    }

    //getters and setters...
}

3
你可以使用一个 "集合(Set)" 来代替。 - JonK
你应该提供 WorkPosition 的源代码,关键是重写该类的 equals 和 hashCode 方法。 - yelliver
我添加了WorkPosition类。 - yaylitzis
3个回答

4
我读了这篇文章 How do I remove repeated elements from ArrayList? 但是我的情况不是String,而是对象类型的WorkPosition
由于答案中的解决方案无论您使用String还是其他一些良好的行为对象都没有关系,因此,您需要做的就是从解决方案的角度使您的WorkPosition对象表现良好。
为此,您必须重写两个特定的方法——hashCode()equals(Object),并确保它们按照规范运行。一旦完成这些工作,消除重复项的方法也将对您的对象起作用,就像对String一样。
class WorkPosition {
    @Override
    public boolean equals(Object obj) {
        // The implementation has to check that obj is WorkPosition,
        // and then compare the content of its attributes and arrays
        // to the corresponding elements of this object
        ...
    }
    @Override
    public int hashCode() {
        // The implementation needs to produce an int based on
        // the values set in object's fields and arrays.
        // The actual number does not matter too much, as long as
        // the same number is produced for objects that are equal.
        ...
    }
}

1

只需将 ArrayList 强制转换为 Set 实现。Set 集合不包含重复元素。 示例:

 Set<WorkPosition> set = new HashSet<WorkPosition>(list);

所有放置在List、Set或Map中(作为键或值)的对象都应该有适当的equals定义。请参见Collection.containsMap.containsKeyMap.containsValue

了解更多关于实现equals的实践


1
你可以将你的 List 转换成一个 Set
ArrayList<WorkPosition> info = new ArrayList<>();
Set<WorkPosition> distincts = new HashSet<>(info);

这需要WorkPosition对象覆盖equals(obj)方法和hashCode(),像这样:
public class WorkPosition {

   // your code

    @Override
    public boolean equals(Object obj) {
        // logic here
    }

    @Override
    public int hashCode() {
        // logic here
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接