Object as a key in treemap in java 8

1.2k views Asked by At

CompareObj is a class in java It consists of three attributes String rowKey, Integer hitCount, Long recency

public CompareObj(String string, Integer i) {


    this.rowKey = string;
    this.hitCount = i%10;
    this.recency= (Long) i*1000;
}

Now I created a treeMap

Comparator<CompareObj> comp1 = (e1,e2) -> e1.getHitCount().compareTo(e2.getHitCount());
    Comparator<CompareObj> comp2 = (e1,e2) -> e2.getRecency().compareTo(e1.getRecency());
    Comparator<CompareObj> result = comp1.thenComparing(comp2);
    TreeMap<CompareObj, CompareObj> tM = new TreeMap<CompareObj, CompareObj>(result);

    for(int i=0;i<=1000;i++)
    {

        CompareObj cO = new CompareObj("A"+i, i);
        tM.put(cO,cO);
    }


    for(int i=0;i<=1000;i++)
    {

        CompareObj cO = new CompareObj("A"+i, i);
        CompareObj values = tM.get(cO);
        System.out.println(values.getRowKey()); // Line 28: get Null Pointer Exception
    }

Also I overide hashCode and Equals. Still I get nullponter exception.

@Override
public int hashCode() {
    return  Objects.hash(getRowKey());
}
@Override
public boolean equals(Object obj) {
    if(this==obj) return true;
    if(!(obj instanceof CompareObj)) return false;
    CompareObj compareObj = (CompareObj) obj;
    return Objects.equals(this.getRowKey(), compareObj.getRowKey());
}

Here when I try to retrive value from treemap back I get Null Pointer exception in the line mentioned. How to solve this

If I want to implement comapareTo() of Comaprable interface, how should I implement if there is multiple sort conditions.

1

There are 1 answers

0
Holger On

The first thing to understand, is the NullPointerException. If you get that exception on the exact line

System.out.println(values.getRowKey());

then either System.out or values is null. Since we can preclude System.out being null, it’s the values variable, which contains the result of get and can be null if the lookup failed.

Since you are initializing the TreeMap with a custom Comparator, that Comparatordetermines equality. Your Comparator is based on the properties getHitCount() and getRecency() which must match, which implies that when the lookup fails, the map doesn’t contain an object having the same values as reported by these two methods.

You show that you construct objects with the same values but not the code of these getters. There must be an inconsistency. As Misha pointed out, your posted code can’t be the code you have ran when getting the exception, therefore we can’t help you further (unless you post the real code you ran).