TreeSet not Re-Ordering Itself after Values in it are Changed

时间:2015-05-24 21:23:49

标签: java data-structures comparator

I have a TreeSet in JAVA which orders a custom datatype called 'Node'. However, the TreeSet does not order itself properly.

A link to my complete implementation is at the bottom. Let me explain my probelm in detail first

Here have a custome datatype 'Node'. It has 2 parameters as such. A character and a number associated to it. Say something like:

pair<char,int> node;

in C++.

Here is the code:

 class Node
    {
        char c;int s;
        Node(char x,int y)
        {
            c=x;s=y;
        }
    }

I implemented a Comparator for this TreeSet which order the elements in descending order of 's'. So for example we have 2 nodes one is (a,2) and the other is (b,5), the they will be ordered as (b,5);(a,2). However, if their size is the same, the lexicographically smaller character will come first.

TreeSet<Node> ts=new TreeSet<Node>(new Comparator<Node>()
{
    @Override
    public int compare(Node o1, Node o2)
    {
        if(o2.s!=o1.s)
        {
            return o2.s-o1.s;
        }
        return (o1.c-o2.c);
    }
});

Now i input the values as Following:

ts.add(new Node('a',3));
ts.add(new Node('b',2));
ts.add(new Node('c',1));

Now here is the operation I want to perform:

  • Pick the element at the head of the TreeSet. Call it a node. Print it
  • Check for 's' or the number associated with this node. Reduce it by 1
  • If s becomes 0, remove the node all together from the TreeSet
  • Keep performing this expression till the TreeSet is empty

Here is my implementaion:

while(ts.size()!=0)
{
    Node node=ts.first();
    System.out.println(node.c+" "+node.s);//Printing the character and the number associated with it
    if(node.s==1)
    {
        ts.pollFirst();//removing redundant node as reducing it by 1 will become 0
    }
    else
    {
        ts.first().s--;//Reducing it's size
    }
}

Well here is my probelem:

Current Output:                                      Expected Output:

a 3                                                  a 3                                                   
a 2                                                  a 2
a 1 //In this iteration, b has the largest number    b 2
b 2                                                  a 1
b 1                                                  b 1
c 1                                                  c 1

Why is the TreeSet not reordering itself and behaving more like a List? How do I rectify this?

I've gotten used to the idea of a 'Comparator' quite recently so please excuse me for a few goof ups in the implementation if any.

Here is the complete implementation: http://ideone.com/As35FO

1 个答案:

答案 0 :(得分:1)

The TreeSet won't reorder itself when you change the value of the elements. You have to take the elements out and re-add them if you want them to remain ordered:

Node first = ts.pollFirst();
first.s--;
ts.add(first);