Question

I have a problem when comparing generic type, I have a Entry and now I have to compare the key with another key, so without thinking I made the equals ...

private DListNode<Entry<K,V>> findNode(K key){
        DListNode<Entry<K, V>> node = head;

        while(node != null && !node.getElement().getKey().equals(key))
            node = node.getNext();

        return node;
    }

!node.getElement().getKey().equals(key)

But the problem, obviously, is that if I have a string and the caps case exclusion will not happen.... equalsIgnoreCase can't be used of course.

So how can I make this to works with every type? Including the strings with caps

Was it helpful?

Solution

private DListNode<Entry<K,V>> findNode(K key){
    DListNode<Entry<K, V>> node = head;

    while(node != null && !specialEquals(node.getElement().getKey(),key))
        node = node.getNext();

    return node;
}

private static boolean specialEquals(K key1, K key2) {
    if( key1 instanceof String && key2 instanceof String ) {
        return ((String) key1).equalsIgnoreCase((String) key2);
    } else {
        return key1.equals(key2);
    }
} 

OTHER TIPS

If this is a real requirement then there are two logical solutions that come to mind....

first option is to just convert all the key values in the map to lowercase (or uppercase) when you insert them, and then you won't have to worry about case in the compare.

The other option is to use a special wrapper for each Key that does the equals method for you:

class CaseInsensitiveString {
    private final String mystring;

    public CaseInsensitiveString(String val) {
        mystring = val;
    }

    public boolean equals(Object o) {
        return o instanceof CaseSensitiveString
               && mystring.equalsIgnoreCase(((CaseInsensitiveString)o).getString())
    }

    public int hashCode() {
        return mystring.tolowercase().hashCode();
    }

    public String toString() {
        return mystring;
    }
}

Best way, use instanceof keyword

while (node != null && node.getKey() != null) {

    if (key instanceof String) {
        String sKey = (String)key;
        if (node.getKey() instanceof String) {
            String nodeKeyString = (String)node.getKey();
            if (nodeKeyString.equalsIgnoreCase(sKey)) {
                return node;
            }
        }
    } else if (node.getKey().equals(key)) {
        return node;
    } else {
        node = node.getNext();
    }
}

Alternatively, if your key are Comparable, you can customize your Comparable to deal with case-insensitive String key value.

I hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top