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
Create a new class that wraps your Blog object and provides the equality/hashcode method you need. For maximum efficiency I would add two static methods on the wrapper, one to convert Blogs list -> Blog Wrapper list and the other to convert Blog Wrapper list -> Blog list. Then you would:
Code for Blog Wrapper would be something like this:
import java.util.ArrayList;
import java.util.List;
public class BlogWrapper {
public static List unwrappedList(List blogWrapperList) {
if (blogWrapperList == null)
return new ArrayList(0);
List blogList = new ArrayList(blogWrapperList.size());
for (BlogWrapper bW : blogWrapperList) {
blogList.add(bW.getBlog());
}
return blogList;
}
public static List wrappedList(List blogList) {
if (blogList == null)
return new ArrayList(0);
List blogWrapperList = new ArrayList(blogList
.size());
for (Blog b : blogList) {
blogWrapperList.add(new BlogWrapper(b));
}
return blogWrapperList;
}
private Blog blog = null;
public BlogWrapper() {
super();
}
public BlogWrapper(Blog aBlog) {
super();
setBlog(aBlog);
}
public boolean equals(Object other) {
// Your equality logic here
return super.equals(other);
}
public Blog getBlog() {
return blog;
}
public int hashCode() {
// Your hashcode logic here
return super.hashCode();
}
public void setBlog(Blog blog) {
this.blog = blog;
}
}
And you could use this like so:
List myBlogWrappers = BlogWrapper.wrappedList(your blog list here);
Set noDupWrapSet = new HashSet(myBlogWrappers);
List noDupWrapList = new ArrayList(noDupSet);
List noDupList = BlogWrapper.unwrappedList(noDupWrapList);
Quite obviously you can make the above code more efficient, particularly by making the wrap and unwrap methods on Blog Wrapper take collections instead of Lists.
An alternative route to wrapping the Blog class would be to use a byte code manipulation library like BCEL to actually change the equals and hashcode method for Blog. But of course, that could have unintended consequences to the rest of your code if they require the original equals/hashcode behaviour.