简体   繁体   English

Java中的多层哈希

[英]Multi-layered Hash in Java

In Perl if I want to have a multi-layered hash, I would write: 在Perl中,如果我想要一个多层哈希,我会写:

$hash_ref->{'key1'}->{'key2'}='value';

Where 'key1' might be a person's name, 'key2' might be "Savings Account" (vs. "Checking Account") and 'value' might be the amount of money in the account. 'key1'可能是某人的姓名, 'key2'可能是“储蓄账户”(与“支票账户”相对), 'value'可能是账户中的金额。

Is there an equivalent to this in Java, ie access values via hash references? 在Java中是否存在等价的东西,即通过哈希引用访问值? What's the syntax like for this? 这个语法是什么样的? Any examples or other resource references would be greatly appreciated. 任何示例或其他资源参考将不胜感激。 Thanks! 谢谢!

In Java, we use objects. 在Java中,我们使用对象。 We would have a Person object, with a name property of type String , and a savingsAccount of type Account . 我们将有一个Person对象,其name属性为String类型, savingsAccount类型为Account This Account object would have a value property, of type BigDecimal . Account对象具有BigDecimal类型的value属性。

Java is an OO language. Java是一种OO语言。 It's not Perl. 这不是Perl。 You should use Java idioms in Java, and not Perl idioms. 你应该在Java中使用Java习语,而不是Perl习语。

You can have a Map<Map<..>> , where you'll be able to call map.get("key1").get("key2") 你可以有一个Map<Map<..>> ,你可以在这里调用map.get("key1").get("key2")

But note that Java is a statically-typed, object-oriented language. 但请注意,Java是一种静态类型的,面向对象的语言。 So you'd better creat classes: Person , SavingsAccount , and a Person has a field private SavingsAccount savingsAcount . 因此,您最好创建类: PersonSavingsAccountPerson有一个private SavingsAccount savingsAcount字段。 Then you'll be able to do a compile-time safe: map.get("John").getSavingsAccount() 然后你就可以做一个编译时安全: map.get("John").getSavingsAccount()

您可以使用equalshashCode方法的正确实现来创建表示密钥的类:

我不确定为什么这个问题被低估了,但回答你的问题,在Java中你可以使用嵌套的Map来实现同样的目的。

For instance, you can have a 例如,你可以有一个

HashMap<String, HashMap<String, BigDecimal>>. 

I would not call it OOD, but you can. 我不会称之为OOD,但你可以。

It would probably be a bit more readable if you had a class for representing Person, a class to represent PersonalAccounts, which has Account instances as attributes, one for each account type (I assume those would be very few, otherwise a list would be better). 如果你有一个代表Person的类,一个代表PersonalAccounts的类,它有一个类作为属性,一个代表每个帐户类型一个,我可能会更具可读性(我认为这些很少,否则列表会更好) )。

Then a single 然后一个

HashMap<Person, PersonalAccounts> 

is enough, if you want to use an HashMap. 如果你想使用HashMap就足够了。

Actually you don't even need a map if an instance of PersonalAccounts is an attribute of a Person. 实际上,如果PersonalAccounts的实例是Person的属性,您甚至不需要地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM