简体   繁体   English

在 Java 中嵌套 collections(包含字符串键的哈希图列表,arrayList 值)

[英]Nesting collections in Java (list of hashmaps containing String key, arrayList value)

Is nesting collections in Java something that I should be doing?我应该在 Java 中嵌套 collections 吗?

I'm currently working on a project where I want to have a bunch of hashmaps that would contain a String key and an arrayList value.我目前正在做一个项目,我想拥有一堆包含字符串键和 arrayList 值的哈希图。 That way when I create and add an object of another class to the collection, it would be able to use some piece of information that if it matched up with one of the keys of one of the hashmaps it would then be deposited in the associated arrayList value.这样,当我创建并将另一个 class 的 object 添加到集合中时,它将能够使用一些信息,如果它与其中一个哈希映射的键之一匹配,它将被存放在相关联的 Z8DC4BB771CF6C82F6C8AEB7D价值。 That way the list can later on be accessed through the correct key for a specific hashmap.这样,以后可以通过特定 hashmap 的正确密钥访问该列表。

Is this a good idea?这是一个好主意吗? Or is it too convoluted and if so is there a better way to do this?还是太复杂了,如果是这样,有更好的方法吗?

There are times to nest, for sure.当然,有时会筑巢。 But in the humble opinion of this seasoned dev, you shouldn't do it unless you have a good reason.但在这个经验丰富的开发人员的拙见中,除非你有充分的理由,否则你不应该这样做。 All too often you would be much better off with some class that represents the inner collection.经常使用一些代表内部集合的 class 会好得多。

So if you find yourself with a Map<String,List<Foo>> ask yourself what that List<Foo really represents.因此,如果您发现自己有一个Map<String,List<Foo>>问问自己List<Foo真正代表什么。 If it's Map<String,List<Student>> then maybe you need Map<String, Roster> or Map<String, Team> .如果是Map<String,List<Student>>那么也许你需要Map<String, Roster>Map<String, Team> I find this yields faster time to market and fewer bugs.我发现这可以缩短上市时间并减少错误。 The fact you're asking the question means you think there's a chance that might be true too.你问这个问题的事实意味着你认为这也有可能是真的。

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

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