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

Java 如何从ArrayList中删除重复的元素(myClass的对象),java,arraylist,Java,Arraylist,我有一个数组列表 ArrayList<WorkPosition> info = new ArrayList<>(); 有没有办法删除额外的外观? 我读过这篇文章,但在我的例子中,我没有字符串,而是工作位置类型的对象 public class WorkPosition { private int id; ArrayList<Integer> machines = new ArrayList<>(); ArrayList&l

我有一个数组列表

ArrayList<WorkPosition> info = new ArrayList<>();
有没有办法删除额外的外观? 我读过这篇文章,但在我的例子中,我没有
字符串
,而是
工作位置
类型的对象

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...
}
公共类工作职位{
私有int-id;
ArrayList机器=新的ArrayList();
ArrayList瓶子=新的ArrayList();
公共工作位置(内部id、ArrayList机器、ArrayList瓶子){
this.id=id;
这个机器=机器;
this.kaloupia=kaloupia;
}
//接球手和接球手。。。
}

只需将
数组列表
强制转换为
实现。集合集合不包含重复的元素。 例如:

 Set<WorkPosition> set = new HashSet<WorkPosition>(list);
Set Set=newhashset(列表);
列表、集合或映射(作为键或值)中的所有对象都应具有适当的相等定义。看,还有


阅读更多信息。

您可以将
列表
转换为
集合

ArrayList<WorkPosition> info = new ArrayList<>();
Set<WorkPosition> distincts = new HashSet<>(info);
我读过这篇文章,如何从
ArrayList
中删除重复的元素?但是在我的例子中,我没有
String
s,而是
WorkPosition

由于答案中的解决方案并不关心您是否使用
String
s或其他行为良好的对象,因此您需要做的就是从解决方案的角度使
WorkPosition
对象行为良好

为此,您必须重写两个特定的方法-
hashCode()
equals(Object)
,并确保它们的行为符合规范。一旦完成此操作,消除重复的方法将适用于您的对象,就像它适用于
String
s一样

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.
        ...
    }
}

您可以使用
集合
而不是提供WorkPosition源代码,该键位于该类的equals&hashcode上方。我添加了
WorkPosition
public class WorkPosition {

   // your code

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

    @Override
    public int hashCode() {
        // logic here
    }
}
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.
        ...
    }
}