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

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

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

    How do i do this?

    In case you also mean how do I make the object immutable and prevent subclassing: use the final keyword

    public final class Blog { //final classes can't be extended/subclassed
       private final String title; //final members have to be set in the constructor and can't be changed
       private final String author;
       private final String url;
       private final String description;
        ...
    }
    

    Edit: I just saw some of your comments and it seems you want to change the class but can't (third party I assume).

    To prevent duplicates you might use a wrapper that implements appropriate equals() and hashCode(), then use the Set aproach mentioned by the others:

     class BlogWrapper {
       private Blog blog; //set via constructor etc.
    
       public int hashCode() {
         int hashCode = blog.getTitle().hashCode(); //check for null etc.
         //add the other hash codes as well
         return hashCode;
       }
    
       public boolean equals(Object other) {
         //check if both are BlogWrappers
         //remember to check for null too!
         Blog otherBlog = ((BlogWrapper)other).getBlog(); 
         if( !blog.getTitle().equals(otherBlog.getTitle()) {
           return false;
         }
         ... //check other fields as well
         return true
       }
     }
    

    Note that this is just a rough and simple version and doesn't contain the obligatory null checks.

    Finally use a Set, loop through all the blogs and try to add new BlogWrapper(blog) to the set. In the end, you should only have unique (wrapped) blogs in the set.

提交回复
热议问题