ArrayList as key in HashMap

前端 未结 9 1858
Happy的楠姐
Happy的楠姐 2020-11-29 09:17

Would it be possible to add an ArrayList as the key of HashMap. I would like to keep the frequency count of bigrams. The bigram is the key and the

9条回答
  •  野性不改
    2020-11-29 09:57

    Yes you can have ArrayLists as a keys in a hash map, but it is a very bad idea since they are mutable.

    If you change the ArrayList in any way (or any of its elements), the mapping will basically be lost, since the key won't have the same hashCode as it had when it was inserted.

    The rule of thumb is to use only immutable data types as keys in a hash map. As suggested by Alex Stybaev, you probably want to create a Bigram class like this:

    final class Bigram {
    
        private final String word1, word2;
    
        public Bigram(String word1, String word2) {
            this.word1 = word1;
            this.word2 = word2;
        }
    
        public String getWord1() {
            return word1;
        }
    
        public String getWord2() {
            return word2;
        }
    
        @Override
        public int hashCode() {
            return word1.hashCode() ^ word2.hashCode();
        }
    
        @Override
        public boolean equals(Object obj) {
            return (obj instanceof Bigram) && ((Bigram) obj).word1.equals(word1)
                                           && ((Bigram) obj).word2.equals(word2);
        }
    }
    

提交回复
热议问题