1

I'm working on a Java generic implementation of AVL trees (the source code is at https://github.com/diningphil/AvlTreeJava), and I've came across a specific problem: if I pass the insert method an argument T key, and then modify the fields of key after insertion, the data structure is corrupted.

How can I avoid this? Can I pass an object requiring that it is not modifiable afterwards by the user but by the implementation of my avl trees?

Thanks in advance

diningphil
  • 396
  • 2
  • 18
  • 2
    In short, it can't be avoided. If the object changes in a way that affects its compareTo methods, then it typically needs to be reinserted. This is why it's recommended to only use immutable objects as keys in for instance `HashMaps`. I think [this q/a](http://stackoverflow.com/questions/7842049/are-mutable-hashmap-keys-a-dangerous-practice) is related. – aioobe Apr 12 '16 at 06:58
  • Just relax and accept that it is impossible to make everything bullet-proof. If the user modifies his keys after insertion, he will corrupt his avl tree. If the restriction is documented, it’s not your business anymore. Compare to `TreeSet` or `HashSet`, both not being immune to changes affecting the order resp. hash code. – Holger Apr 13 '16 at 15:19

2 Answers2

1

You can clone the key on insert. This way any changes to the original object will not take effect for the inserted one.

Alexander Petrov
  • 9,723
  • 24
  • 57
1

Unless the data is immutable i don't know how it can be avoided totally, but you could do something to separate the data. What i mean: instead of T extends Comparable<T> the tree can be setup with a passed in Comparator.

Then the client could modify the data after insertiont without corrupting the tree provided it modifies only the fields not used in the Comparator. This is forcing the client to think what he wants and does not want to modify and provides a little bit of flexibility.

AdrianS
  • 1,780
  • 7
  • 26
  • 48