Sorting custom data structure on Key in TreeMap?

The problem is that your implementation of compareTo is not consistent with equals, which is required by TreeMap From the API docs.

The problem is that your implementation of compareTo is not consistent with equals, which is required by TreeMap. From the API docs: Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. One possible consistent implementation would be to first compare by rank and then by name if the rank values are equal.

For two instances of Custom with equal ranks and identical names you should not expect to be able to store them both as keys within the same Map - This violates the contract of Map. Public int compareTo(Custom o) { int ret = this. Rank - o.

Rank; // Equal rank so fall back to comparing by name. If (ret == 0) { ret = this.name. CompareTo(o.Name); } return ret; }.

1 +1. Another problem is that you return -1 for two objects having the same rank, and this means that you are in a situation where you have A Rank - o.rank. Its possibly a safe assumption here.

Even though its an int it probably doesn't need to be. – Peter Lawrey Sep 12 at 9:04 @Peter - Fair point and to be honest I did it this way to keep the example code small. – Adamski Sep 12 at 10:30.

As mentioned, your implementation of equals and compareTo are not consistent with each other. If I read your question correctly, what you require is to preserve duplicates that have the same key. I'd recommend you to look into the TreeMultimap of the Google Guava collections.It creates set containers for each value object sothat different values having the same key are preserved.

E.g. TreeMultimap. Put ("rank1", "Joe"); treeMultimap.

Put ("rank1", Jane"); treeMultimap. Get ("rank1"); // Set("Joe","Jane"); The constrain in this data structure is that K,V pairs must be unique. That is, you can't insert ("rank1", "Joe") twice in the Multimap.

One important note: The reason why you see so many examples of Map, using simple types and, in particular, strings, is that keys in a map must be immutable. The equals and hashcode values of an object must not change in the time it's used as a key in a map. Translated to your example, you cannot do customObject.

SetRank(...) and updates a rank value when it's used as a key. To do so, you first need to remove the key and its values, update it and then insert it again.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions