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

时间:2015-10-13 10:03:39

标签: java arraylist

我有一个Arraylist

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

在某些方面,我添加了一些对象。最后,这个arrayList有多次相同的对象。该对象有一些int值和2个arraylists

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]

有没有办法删除额外的外观? 我看过这个How do I remove repeated elements from 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 个答案:

答案 0 :(得分:4)

  

我读过这篇如何删除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 :(得分:1)

只需将ArrayList转换为Set实施。 Set集合不包含重复元素。 例如:

 Set<WorkPosition> set = new HashSet<WorkPosition>(list);
放置在List,Set或Map(作为键或值)中的

所有对象应具有相应的equals定义。请参阅Collection.containsMap.containsKeyMap.containsValue

详细了解the practice of implementing equals

答案 2 :(得分: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
    }
}