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

后端 未结 21 1655
渐次进展
渐次进展 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

    1. override hashCode() and equals(..) using those 4 fields
    2. use new HashSet(blogList) - this will give you a Set which has no duplicates by definition

    Update: Since you can't change the class, here's an O(n^2) solution:

    • create a new list
    • iterate the first list
    • in an inner loop iterate the second list and verify if it has an element with the same fields

    You can make this more efficient if you provide a HashSet data structure with externalized hashCode() and equals(..) methods.

提交回复
热议问题