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<BlogWrapper>
, 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.