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

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

问题描述

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

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

我必须设计一个 Map,其中 'Keys' 总是 String 类型.但是,其中一个键的"可能是字符串或列表(取决于特定键可以具有的值的数量.值"将是如果该特定键只有一个值,则为字符串,如果键包含多个值,则必须为列表).如何完成这个场景?

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?

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

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?

推荐答案

可以做一些类似Map的事情.

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

但是:我强烈建议重新考虑您的设计.你应该为你的人使用一个类.这样你就可以这样做:MapPerson 具有用于名称、电话号码和其他信息的 getter 和 setter.

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.

示例Person 类:

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天全站免登陆