Alex Rivera | Logout

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

Asked 2011-07-13T14:02:59.313
36

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;
    private String author;
    private String url;
    private String description;
    ...
}

A duplicated object is an object that have title, author, url and description equal to other object.

And I can't alter the object. I can't put new methods on it.

How do I do this?

Edit
Report

2 Answers

10

Use set:

yourList = new ArrayList<Blog>(new LinkedHashSet<Blog>(yourList));

This will create list without duplicates and the element order will be as in original list.

Just do not forget to implement hashCode() and equals() for your class Blog.

answered 2011-07-13T14:07:13.193
0

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<MyObject> list = new ArrayList<MyObject>;
for(MyObject obj1 : list)
{
    for(MyObject obj2 : list)
    {
        if(obj1.equals(obj2)) list.remove(obj1); // or list.remove(obj2);
    }
}
answered 2011-07-13T14:07:18.683

Your Answer