1

In java, and there is one catch here. The objects are already compiled and the hash() and equals() methods therefore cannot be over written. Throwing it into a set, then back into a list will not work because the criteria for uniqueness isn't currently defined in equals() and this cannot be overridden.

1
  • What is your criteria for 'uniqueness' which is not defined in the equals() method? Commented Sep 21, 2011 at 15:33

3 Answers 3

3

You should still be able to create subclasses and create equals and hashcode methods that work, unless the classes/methods are final.

If that is the case, you could use composition, basically create a wrapper for the things you are putting in the collection, and have the wrapper's equals and hashcode implement the contract correctly, for the thing being wrapped.

You are in a tough position, because what I am reading is that the original classes are not following the contract for equals and hashcode which is a real problem in Java. It's a pretty serious bug.

Sign up to request clarification or add additional context in comments.

2 Comments

The point being that if comparison is cheaper, the TreeSet approach may be better. the original question did not say anything about having a good hashcode.
If you have a good hashcode as well, you can also use containment; i.e. use a wrapper rather than a subclass.
1

Write a custom Comparator for your objects and use Collections.sort() to sort your list. And then remove duplicates by going though a list in a loop.

1 Comment

... or use the Comparator with a TreeSet
1

a compareTo method would return -1, 0, 1; if 0, remove from list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.