Java equivalent of Perl's hash

前端 未结 8 1313
粉色の甜心
粉色の甜心 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:14

    Java has hashes, but because of strong typing they're not quite as flexible as hashes in Perl. Multidimensional hashes are harder to work with. In Perl, you can just declare a hash and let autovivification create the nested hashes on demand.

    my %hash;
    $hash{a}{b} = 1;
    

    In Java, you have to declare it to be a hash-of-hashes up-front.

    Map> hash = new HashMap>();
    hash.put("a", new HashMap());
    hash.get("a").put("b", new Integer(1));
    

    For every extra dimension you need to add another nesting of Map to the declaration. Aside from being tedious, this isn't very OO.

提交回复
热议问题