I need to sort a set of java objects using the Level value of an integer. I also need to determine if this collection already contains an object called "title".
I believe the best choice for a collection is TreeSet, to have an ordered set of unique values.
I have an object with the attributes "level" and "title". It implements comparable values:
It overrides the Equals method (to verify that the object is already contained in the TreeSet by "title".
The code looks like this:
@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 try to add values to the list from arraylist with possible duplicate values. Contains does not seem to work, and objects are added to the TreeSet independently. 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);
}
}
, . ?