Nested Maps or combined keys in java

前端 未结 6 1672
一个人的身影
一个人的身影 2020-12-17 21:58

I need a Map to make a cache in Java for same values that I have two String keys. My question it\'s better to make nested Maps (one for each key) or make some type of custom

6条回答
  •  一个人的身影
    2020-12-17 22:59

    I think that using nested maps is less optimal way. I agree with your second thought - implement a custom class with overriden hashCode

    public int hashCode(){
       return str1+str2.hashCode();
    }
    


    and equals

    public boolean equals(Object o){
       //compare both keys here
    }
    

    Also don't forget to override the same methods in the stored object's class.

    Then, in case of ["ab", "c"] you will have the same hash code, but different equals result

提交回复
热议问题