I need to sort a java collection of objects by an Integer value “level”. I also need to determine if this collection already contains an object by “title”.
I believe the best choice of a collection is a TreeSet to have an ordered set of unique values.
I have an object with the “level” and “title attributes. It implements comparable like so:
It overrides the Equals method (for checking if the object is already contained in the TreeSet by “title”.
The code looks like:
@Override
public boolean equals(Object arg0) {
Artifact obj = (Artifact) arg0;
if (this.getTitle().equals(obj.getTitle())) {
return true;
}
return false;
}
@Override
public int compareTo(Artifact aThat) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == aThat) return EQUAL;
if (this.level < aThat.level) return BEFORE;
if (this.level > aThat.level) return AFTER;
assert this.equals(aThat) : "compareTo inconsistent with equals.";
return EQUAL;
}
When I attempt to add values to the list from an arraylist with possibly duplicate values. The contains seems to not work and objects are added to the TreeSet regardless. Here is the code:
TreeSet<Artifact> subsetOfArtifacts = new TreeSet<Artifact>();
ArrayList<Artifact> allArtifacts = getArtifacts();
Iterator<Artifact> allArtifactsIter = allArtifacts.iterator();
while (allArtifactsIter.hasNext()) {
Artifact artifact = (Artifact) allArtifactsIter.next();
if (!subsetOfArtifacts.contains(artifact)) {
subsetOfArtifacts.add(artifact);
}
}
I want to ideally have a list of all unique artifacts sorted by level. How do I accomplish this?
If you override
equals()you should overridehashCode()too! Otherwise, behaviour with collections, especially Sets, is undefined. You should add this method to your class:Next, you should use a HashSet instead and use
Set sortedSet = new TreeSet(set);for the sorting. Once you do that, it should all work OK.The reason is that HashTables rely on the fact that if two objects are
equal()then theirhashCode()is also equal. Here’s an excerpt from the javadoc forhashCode()