I've read so much arguing about "sort by value maps". Well, I wrote the following log(n) sort by value Map . And, by the way, a real Map , does not allow duplicate keys. Many of the maps I googled ignore that annoying problem. I assume this map is still log(n)...:
public static void sortByValue_logN() {
class MyComp implements Comparator {
Map<Object, Integer> sharedMap;
public int compare(Object key1, Object key2) {
if(key1.equals(key2)) { return 0; }
Integer val1 = sharedMap.get(key1);
Integer val2 = sharedMap.get(key2);
if(val1 > val2) return -1;
return 1;
}
}
class TreeMapByValue<K> extends TreeMap<K, Integer> {
Map<Object, Integer> sharedMap = new HashMap<Object, Integer>();
TreeMapByValue(Comparator comp) {
super(comp);
}
@Override
public Integer put(K key, Integer val) {
if(sharedMap.containsKey(key)) {
super.remove(key);
val += sharedMap.get(key);
}
sharedMap.put(key, val);
super.put(key, val);
return val;
}
}
MyComp myComp = new MyComp();
TreeMapByValue<Object> myMap = new TreeMapByValue(myComp);
myComp.sharedMap = myMap.sharedMap;
// all the rest is just testing the map
Random rand = new Random();
String[] story = { "The", "quick", "brown", "fox", "jumped" };
for(int repeat = 0; repeat < 3; repeat++) {
for(int i = 0; i < story.length; i++) {
String key = story[i];
int value = rand.nextInt(100);
myMap.put(key, value);
System.out.println(key + "-->" + value);
}
}
for(Map.Entry<Object, Integer> entry : myMap.entrySet()) {
System.out.println("key = " + entry.getKey() + "___value = " + entry.getValue());
}
}
Surely (at least stylistically) something is bad about the above code.
I don't understand generics yet, so I am ok with ignoring that for now. I am also ignoring thread-safety issues as well.
My goal is to create a log(n) "sort by value" map that respects the property of not having duplicate keys. So, what is wrong with what I did?