这是Name class:
public class Name implements Comparable<Name> {
public String lastName, firstName;
public Name(String last, String first) {
lastName = last; firstName = first;
}
}
这是PhoneBook类,问题出在这个类中:
public class PhoneBook {
private SortedMap<Name, Integer> directory = new TreeMap<Name, Integer>();
public PhoneBook(ArrayList<Name> names, ArrayList<Integer> phones) {
for (int i = 0; i < names.size(); i++) {
directory.put(names.get(i), phones.get(i));
}
}
public void print() {
for (Map.Entry<Name,Integer> entry : directory.entrySet()) {
System.out.print(entry.getKey());
System.out.print(entry.getValue());
System.out.println();
}
}
public static void main(String[] args) {
ArrayList<Integer> phones = new ArrayList<>();
ArrayList<Name> names = new ArrayList<>();
PhoneBook pb = new PhoneBook(names, phones);
phones.add(8888);
phones.add(9999);
names.add(new Name("Shaun-Williams", "Joe"));
names.add(new Name("Baltimore", "Paul"));
pb.print();
}
我不明白我做错了什么,但这并没有印刷任何东西。请帮忙。
答案 0 :(得分:0)
Java不会通过引用传递方法参数,而是传递值,因此传递给该构造函数的值为空,因此在调用print方法时不会打印。
首先初始化对象,然后将构建传递给构造函数,如下所示。
ArrayList<Integer> phones = new ArrayList<>();
ArrayList<Name> names = new ArrayList<>();
phones.add(8888);
phones.add(9999);
names.add(new Name("Shaun-Williams", "Joe"));
names.add(new Name("Baltimore", "Paul"));
//pass the object after you've done your initializations
PhoneBook pb = new PhoneBook(names, phones);
pb.print();
希望article可以提供帮助