0

我正在尝试编译这个程序。它适用于 2 个字符串(姓名、电话号码),但不适用于 3 个字符串(姓名、电话号码和性别)。


代码无效代码 - 3 个字符串(姓名、电话号码和性别)


import java.util.Map;
import java.util.TreeMap;

public class Ann {

String name, phone;

public Ann() {
}

public static void testMap() {
    Map<String, String, String> theMap = new TreeMap<String, String,String>();
    // new HashMap<K,V>(); could also be used
    theMap.put("Roger M", "090-997-2918", "Male");
    theMap.put("Jane M", "090-997-1987", "FeMale");
    theMap.put("Stacy K", "090-997-9188", "FeMale");
    theMap.put("Gary G", "201-119-8765", "Male");
    theMap.put("Jane M", "090-233-0000", "FeMale");
    System.out.println("Testing TreeMap and Map");
    System.out.print("Stacy K has phone ");
    System.out.print(theMap.get("Stacy K"));
    System.out.print("\n");

    System.out.print("Jane M has phone ");
    System.out.print(theMap.get("Jane M"));
} // testMap()

public static void main(String[] args) {
    testMap();

}
}

错误

wrong number of type arguments; required 2

wrong number of type arguments; required 2


工作代码对于 2 个字符串(姓名、电话号码)


import java.util.Map;
import java.util.TreeMap;

public class Ann {

String name, phone;

public Ann() {
}

public static void testMap() {
    Map<String, String> theMap = new TreeMap<String, String>();
    // new HashMap<K,V>(); could also be used
    theMap.put("Roger M", "090-997-2918");
    theMap.put("Jane M", "090-997-1987");
    theMap.put("Stacy K", "090-997-9188");
    theMap.put("Gary G", "201-119-8765");
    theMap.put("Jane M", "090-233-0000");
    System.out.println("Testing TreeMap and Map");
    System.out.print("Stacy K has phone ");
    System.out.print(theMap.get("Stacy K"));
    System.out.print("\n");

    System.out.print("Jane M has phone ");
    System.out.print(theMap.get("Jane M"));
    } // testMap()

public static void main(String[] args) {
    testMap();

}
}

我希望代码适用于大约 5 个属性,例如姓名、电话、性别、年龄、地址。如果有人可以帮助我编译问题顶部的代码,我可以弄清楚其余的。

谢谢

4

1 回答 1

8

您不能随意将类型参数添加到泛型类型中 - 它们是用一定数量定义的,并且必须使用那么多(忽略原始类型)。类型参数对实现有特定的意义——HashMap如果你调用,类怎么知道你想得到什么map.get(name)

您应该将所有属性封装到一个类中(例如Personor Contact),然后创建一个Map<String, Person>从名称到人员的映射。例如:

public enum Gender
{
    FEMALE, MALE;
}

public final class Person
{
    private final String name;
    private final Gender gender;
    private final Date dateOfBirth;
    private final String address;
    private final String telephone;

    public Person(String name, Gender gender, Date dateOfBirth,
                  String address, String telephone)
    {
        // You probably want to put some validation in here
        this.name = name;
        this.gender = gender;
        this.dateOfBirth = dateOfBirth;
        this.address = address;
        this.telephone = telephone;
    }

    public String getName()
    {
        return name;
    }

    // etc for the other properties
}

...

Map<String, Person> map = new HashMap<String, Person>();
Person jon = new Person("Jon", Gender.MALE, /* etc */);
map.put("Jon", jon);
于 2010-07-10T07:55:09.073 回答