在java中具有多种类型值的地图 [英] Maps with multiple types of values in java

查看:117
本文介绍了在java中具有多种类型值的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须完成一个奇怪的奇特场景。它描述如下:



我必须设计一个地图,其中始终为 String 类型。然而,其中一个键的可能是字符串或列表(取决于特定键可以具有的值的数量,值将是一个String,如果该特定键只有一个值,并且如果键包含许多值,则必须为列表)。如何完成这种情况?



例如:地图中有2个键,即名称和电话号码。一个人只能有一个名字和多个电话号码。所以这里的第一个键,即名称应该具有值的String类型,而对于第二个键,即电话号码应该具有值的列表类型。如何申报这样的地图。可以吗?

解决方案

可以做一些类似 Map< String,Object> code>。



:我强烈建议您认为自己的设计。你应该为你的人使用一个班级。您可以这样做:映射< String,Person> Person 具有名称,电话号码和其他信息。



示例类:

  public class Person {

private String name;
私人列表< String> phoneNumbers = Collections.emptyList();

public void setName(String name){
this.name = name;
}

public String getName(){
return name;
}

public void setPhoneNumbers(List< String> phoneNumbers){
this.phoneNumbers = phoneNumbers;
}

public void addPhoneNumber(String number){
phoneNumbers.add(number);
}

public List< String> getPhoneNumbers(){
return phoneNumbers;
}
}


I have to accomplish a strange peculiar scenario. Its described as follows:

I have to design a Map where the 'Keys' are always of String type. However, the 'Value' for one of the key may be a String or a List(depends on the number of values a particular key can have. 'Value' will be a String if that particular key has only one value and it has to be a List if the key contains many values). How to accomplish this scenario?

For Example: there are 2 keys in a map namely "Name" and "Phone Nos". A person can have only one name and multiple phone numbers. So here the first key i.e. "Name" should have 'String' type for Value, whereas for the second key i.e. "Phone Nos" should have 'List' type for Value. How to declare such a Map. Is it possible?

解决方案

It is possible to do something like Map<String, Object>.

But: I would strongly suggest to think your design over. You should use a class for your persons instead. That way you could do: Map<String, Person> with Person having getters and setters for names, phone numbers and other information.

Example Person class:

public class Person {

    private String name;
    private List<String> phoneNumbers = Collections.emptyList();

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setPhoneNumbers(List<String> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }

    public void addPhoneNumber(String number) {
        phoneNumbers.add(number);
    }

    public List<String> getPhoneNumbers() {
        return phoneNumbers;
    }
}

这篇关于在java中具有多种类型值的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆