/java/

List and remove method

2013-04-28 23:18:45

If you have Post object with hashCode and equals method. And this method check only id and name.

You can test something like this. Add two similar object:

Post postA = new Post(1L,"lorem1","1"); Post postB = new Post(1L,"lorem1","2");

And create object to remove. Post toRemove = new Post(1L,"lorem1","5");

What do you think happened ?

List

<post> posts = new ArrayList<post>();

Post postA = new Post(1L,"lorem1","1");
Post postB = new Post(1L,"lorem1","2");
Post postC = new Post(2L,"lorem2","3");

posts.add(postA);
posts.add(postB);
posts.add(postC);

for(Post _post : posts){
    log(_post.getId()+" / "+_post.getName());
}

log("====================================");

Post toRemove = new Post(1L,"lorem1","5");
posts.remove(toRemove);

for(Post _post : posts){
    log(_post.getId()+" / "+_post.getName());
}

Only one object is removed.

If you know that the same/similar object are added few times you can use:

Post toRemove = new Post(1L, "lorem1", "5");

List objectsToRemove = new ArrayList<post>();
objectsToRemove.add(toRemove);
posts.removeAll(objectsToRemove);

Post.java

public class Post {
    private long id;
    private String name;
    private String desc;

    public Post(long id, String name, String desc){
        this.id = id;
        this.name = name;
        this.desc = desc;
    }

    //getters and setters

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + (int) (this.id ^ (this.id &gt;&gt;&gt; 32));
        hash = 79 * hash + (this.name != null ? this.name.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Post other = (Post) obj;
        if (this.id != other.id) {
            return false;
        }
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        return true;
    }   
}