-3

I was checking tree set and notice that I am unable to update the value in Tree set for my user defined Object

e.g

class Emp implements Comparable<Emp>
{
int id;
String name;

public Emp(int id,String name)
{
    this.id=id;
    this.name=name;
}

@Override
public int compareTo(Emp obj) {
        if(obj.id>this.id)
            return -1;
        else if(obj.id<this.id)
            return 1;
        else
            return 0;
}

@Override
public String toString() {
    return "Emp Id:"+id+" Emp Name:"+name;
}
}
public static void main(String[] args) {
    treesetwithCustom();
}

public static void treesetwithCustom()
{
    TreeSet<Emp> set=new TreeSet<Emp>();
    set.add(new Emp(1,"ABC"));
    set.add(new Emp(2,"XYZ"));
    set.add(new Emp(1,"PQR"));
    System.out.println(set);
}

When I print the set it shows the value for Emp ID 1 as ABC and not PQR

when I check in rt.jar for tree set implementation I notice there seems to be a bug in Implementation as TreeSet Internally uses implementation provided by TreeMap and call put method of TreeMap.

In rt.jar the put code Update the value and not Key and in TreeSet the value for Key is always passed as present

Please help me understand if is there any way to achieve the update in tree set and if my understanding is correct about the bug.

1 Answers1

0

As others have already explained, the described behaviour is to be expected and explicitly specified in the JDK API description for class TreeSet.

If you are looking for a way to keep your collection up to date, check out my UpdateableTreeSet implementation. There are a few articles here on SO which relate to the same problem and also to UpdateableTreeSet:

Community
  • 1
  • 1
kriegaex
  • 63,017
  • 15
  • 111
  • 202