Does TreeMap put () silently delete other entries?

I experienced some really ghostly TreeMap behavior, and I had some problems narrowing a small test case, so bear with me.

I want to read a large number of key-value pairs in a Map from a file provided at runtime. I use my own key class. Later, when I go to pull out the records, I discovered that one or more of them are missing. Using a debugger and some test cases, I decided that the missing record (s) definitely disappears during the read phase, but I'm not sure what causes it.

Basically:

Map<MyKey,Double> map = new TreeMap<MyKey,Double>();
map.put(key1,value1);

// ... put another ~500 entries into the map ...

assertTrue(map.containsKey(key1)); // passes
if (!map.containsKey(keyN)) { 
    map.put(keyN, valueN); // this code executes
}
assertTrue(map.containsKey(key1)); // FAILS

... Thus, adding a new key to the card leads to the fact that an unrelated record may drop out of it.

  • key1 keyN, key1 - 500 -
  • 2.. (N-1), key1 N
  • 2.. (N-1), key1 , N, , () keyQ, ~ 300
  • , , keyN 1, , keyQ 1, , ,
  • HashMap , key1
  • MyKey Comparable, equals hashCode.

TreeMap, , TreeMap - . HashMap , , TreeMap - , ?

+5
3

TreeMap , , 0. , key1 keyN ' ' 0, key1 N, (). , !key1.equals(keyN). , , , , TreeMap , .

, , , 0. , , , "".

javaadocs:

... map compareTo ( ) , , , , ...

javadocs ( @Brian):

( ), . , ( ) "", ( ), . , ( map) ( ), equals.

+11

MyKey. , - compareTo. , compareTo equals.

+1

Are you sure keyN does not overwrite key1 in any scenario? Because it seems to me that your case is phantom.

0
source

All Articles