Reputation: 5526
I am trying to get a hang of using custom comparator with TreeSet. However, it seems like something is wrong. I see duplicates no matter whether I use custom equals or the compare from comparator.. Any idea where is the mistake? Below is the code: (Please look at comments to follow)
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
public class TreemapTest {
public static void main(String[] args) {
//Take an array of integers
int list[] = { 1,2,3,4,2,4,2,5 };
//Create a list of custom objects
ArrayList<Element> elements = new ArrayList<Element>();
//Populate the list with values from int array
for (int v : list){
elements.add(new Element(v));
}
/** Attempt to create a treeset from the arraylist */
// Create the Treeset with custom comparator
TreeSet<Element> nt = new TreeSet<Element>(new Comparator<Element>(){
public int compare(Element a, Element b){
System.out.println("Comparing "+ a.val + " and "+ b.val);
if ( a.val == b.val )
return 0;
if ( (a.val - b.val) > 0 )
return 1;
return -1;
}
});
// Add the elements into the treeset
for (Element elem: elements ){
nt.add(elem);
}
// Output shall not contain duplicates
for (Element elem: elements ){
System.out.print(":"+elem.val);
}
}
}
class Element {
public int val;
Element(int v){
val = v;
}
// boolean equals(Element e){
// return this.val == e.val;
//
// }
}
Upvotes: 0
Views: 900
Reputation: 6461
You are printing the elements
list again, change it to nt
set.
// Output shall not contain duplicates
for (Element elem: nt){
System.out.print(":"+elem.val);
}
Upvotes: 5