How to remove duplicate objects in a List without equals/hashcode?

后端 未结 21 1606
渐次进展
渐次进展 2020-12-03 02:53

I have to remove duplicated objects in a List. It is a List from the object Blog that looks like this:

public class Blog {
    private String title;
    priv         


        
21条回答
  •  不思量自难忘°
    2020-12-03 03:30

    First override equals() method:

    @Override
    public boolean equals(Object obj)
    {
        if(obj == null) return false;
        else if(obj instanceof MyObject && getTitle() == obj.getTitle() && getAuthor() == obj.getAuthor() && getURL() == obj.getURL() && getDescription() == obj.getDescription()) return true;
        else return false;
    }
    

    and then use:

    List list = new ArrayList;
    for(MyObject obj1 : list)
    {
        for(MyObject obj2 : list)
        {
            if(obj1.equals(obj2)) list.remove(obj1); // or list.remove(obj2);
        }
    }
    

提交回复
热议问题