[英]Map's value is an object. How can I use/iterate through all those variables? (Java)
I have data that describes people - they all have an ID, hair color, eye color, age, etc. A People class contains those values. 我有描述人的数据-他们都有ID,头发颜色,眼睛颜色,年龄等。People类包含这些值。 I made a map like this in an other class:
我在另一堂课上做了这样的地图:
private static Map<Integer, People> people = new HashMap<Integer, People>();
I made a getPeople() method for it, so I could use it elsewhere. 我为此创建了一个getPeople()方法,因此可以在其他地方使用它。
When I'm trying to get the values of my "people" map, I get it back as a long string, like brownblue6 which is ok, because I get the right values back, but I need to use them one by one. 当我尝试获取“人物”地图的值时,我会以长字符串的形式将其取回,就像没问题的Brownblue6一样,因为我会获得正确的值,但是我需要一个一个地使用它们。
So let's say, I need to do something with the person's ID or get the person's hair color if that person has blue eyes. 假设我们要用该人的ID做些事情,或者如果该人有蓝眼睛,则要弄清该人的头发颜色。
How can I iterate through those values or get only the "eyeColor" string's value? 如何遍历这些值或仅获取“ eyeColor”字符串的值? Do I really need to use Map here or is there another easier way for this?
我真的需要在这里使用Map还是有另一种更简单的方法? (The things that describe people must stay in a separate class, I can't change that.)
(描述人的事物必须放在一个单独的类中,我无法更改。)
It's not clear whether or not you need a map - or even what key you're using. 目前尚不清楚您是否需要地图-甚至不需要使用什么钥匙。 Unless you need to look things up by key, you probably just want a
List<People>
- and you should probably rename your type to Person
if it's meant to represent a single person per instance, which looks more likely. 除非你需要关键要看东西,你可能只是想要一个
List<People>
-你应该你的类型可能重命名为Person
,如果它的意思是代表每个实例的一个人,看起来更容易。 At that point, you could use: 此时,您可以使用:
for (Person person : foo.getPeople() {
String eyeColor = person.getEyeColor();
// Do whatever you need
}
Firstly, people means persons . 首先, 人是指人 。 I suspect that you might have wanted something like this:
我怀疑您可能想要这样的东西:
private static Map<Integer, Person> people = new HashMap<Integer, Person>();
After that, you can use enhanced-for-loop to iterate over the map. 之后,您可以使用Enhanced-for循环对地图进行迭代。 For example:
例如:
for(Map.Entry<Integer, Person> person: people.entrySet())
{
String hair = person.getHairColor();
//... You can retrieve other features as well.
}
Since you haven't provided your class code, I'll have to guess at field names, etc., but this seems like it should accomplish what you want: 由于您尚未提供类代码,因此我不得不猜测字段名称等,但这似乎应该可以完成您想要的工作:
// Get the people (which are values, as opposed to keys) of the map.
Collection<Person> people = getPeople().values();
// Iterate over each person.
for (Person somePerson : people) {
// Do something with the eye color.
System.out.println("This eye color is " + somePerson.eyeColor);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.