开发者

Compare 2 keys in Java HashMap

I've made a BinaryTree< HashMap<String, String> >.

How can I compare the two keys so I can correctly insert the two elements (HashMaps) into the ordered BinaryTree? Here's what I've got so far:

public class MyMap<K extends Comparable<K>, V> extends HashMap<K, V> implements Comparable< MyMap<K, V> >
{

    @override
    public int compareTo(MyMap<K, V> mapTwo)
    {
        if ( (this.keySet().equals(mapTwo.keySet())) ) return 0;
        //How can I check for greater than/less than and keep my generics?  

    }

E开发者_如何转开发DIT: There is only one key in each HashMap (it's a very simple language translation system), so sorting the keys shouldn't be necessary. I would have liked to use the String.compareTo() method, but because of my generics, the compiler doesn't know that K is a String


I think you've picked a bad data structure.

HashMaps are not naturally ordered. The keys in the set for a HashMap have an unpredictable order that is sensitive to the sequence of operations that populated the map. This makes it unsuitable for comparing two HashMaps.

In order to compare a pair of HashMaps, you need to extract the respective key sets, sort them and then compare the sorted sets. In other words, a compareTo method for HashSet derived classes is going to be O(NlogN) on average.


FWIW, a compareTo implementation would look something like this, assuming that the method is to order the HashMaps based on the sorted lists keys in their respective key sets. Obviously, there are other orderings based on the key sets.

public int compareTo(MyMap<K, V> other) {
    List<K> myKeys = new ArrayList<K>(this.keySet());
    List<K> otherKeys = new ArrayList<K>(other.keySet());
    Collections.sort(myKeys);
    Collections.sort(otherKeys);
    final int minSize = Math.min(myKeys.size(), otherKeys.size());
    for (int i = 0; i < minSize; i++) {
        int cmp = myKeys.get(i).compareTo(otherKeys.get(i));
        if (cmp != 0) {
            return cmp;
        }
    }
    return (myKeys.size() - otherKeys.size());
}

If there is only ever one key / value pair in the map, then you should replace it with a simple Pair<K,V> class. Using a HashMap to represent a single pair is ... crazy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜