Java equivalent of Perl's hash

前端 未结 8 1312
粉色の甜心
粉色の甜心 2021-01-18 02:05

I\'ve been using a lot Perl hashes due to super flexibility and convenient. for instance, in Perl I can do the following:

$hash{AREA_CODE}->{PHONE}->{S         


        
8条回答
  •  醉酒成梦
    2021-01-18 02:31

    You can easily subclass your hash to add a method that'll autovivify for you.

    From: $hash{AREA_CODE}->{PHONE}->{STREET_ADDR}

    To: hash.vivifyingGet(areaCode).put(phone, streetAddr).

    Assuming I've created the hash with:

    /**
      * A two-level autovivifying hashmap of X and Y to Z. Provides
      * a new method #vivifyingGet(X) which creates the next level of hash.
      */
    Map> hash =
        new HashMap>() {
        /**
          * Convenience method to get or create the next level of hash.
          * @param key the first level key
          * @return the next level map
          */
        public Map vivifyingGet(Phone key) {
            if (containsKey(key)) {
                return get(key);
            } else {
                Map = hash = new HashMap();
                put(key, hash);
                return hash;
            }
        }
    };
    

提交回复
热议问题