ArrayList.add()没有添加到ArrayList

时间:2016-04-07 00:20:27

标签: java arraylist

我正在尝试添加从PhoneBookEntry类的构造函数创建的一些名称和电话号码,将它们存储在PhoneBook类内部的ArrayList中,然后能够打印出数组列表。

public class Application {
  public static void main(String[] args) {
    PhoneBookEntry name1 = new PhoneBookEntry("Cameron", "1-425-415-7157");
    PhoneBookEntry name2 = new PhoneBookEntry("Mike", "1-748-142-2341");
    PhoneBookEntry name3 = new PhoneBookEntry("Riles", "1-471-648-1782");
    PhoneBookEntry name4 = new PhoneBookEntry("Tom", "1-427-145-6471");
    PhoneBookEntry name5 = new PhoneBookEntry("Billy", "1-718-545-5715");
  }
}


import java.util.ArrayList;

public class PhoneBookEntry {

PhoneBook book = new PhoneBook();

public PhoneBookEntry(String name, String phoneNumber) {
    book.add(name, phoneNumber);
}

public void printEntries() {
    for(int i = 0; i < names.size(); i++) {
        System.out.println("Name #"+(i + 1)+": "+names.get(i));
    }
}

}


import java.util.ArrayList;

public class PhoneBook {
   ArrayList<String> names = new ArrayList<String>();
  ArrayList<String> phoneNumbers = new ArrayList<String>();

public void add(String name, String phoneNumber) {
    names.add(name);
    System.out.println(name + " added to the arraylist!");
    System.out.println(names.size());
    phoneNumbers.add(phoneNumber);
}

public void print() {
    for (int i = 0; i < names.size(); i++) {
        System.out.println("Name #" + (i + 1) + ": " + names.get(i));
    }
    for (int i = 0; i < phoneNumbers.size(); i++) {
        System.out.println("Phone Number #" + (i + 1) + ": " + phoneNumbers.get(i));
    }
}
}

当前输出:

Cameron added to the arraylist!
1
Mike added to the arraylist!
1
Riles added to the arraylist!
1
Tom added to the arraylist!
1
Billy added to the arraylist!
1

3 个答案:

答案 0 :(得分:3)

这是因为您为每个PhoneBook创建了一个新的PhoneBookEntry,最后有五个列表,每个列表都有一个条目。

您的代码可能看起来更像

public static void main(String[] args) {
   PhoneBook book = new PhoneBook();
   book.add("Cameron", "1-425-415-7157");
   book.add("Mike", "1-748-142-2341");
}

答案 1 :(得分:1)

您每隔count($maps_clean)创建一个新的PhoneBook

PhoneBookEntry成为一个字段:

PhoneBook book

并使用每个新的public PhoneBook book = new PhoneBook();对象简单地将每个新条目添加到其中。或者只是在主要内容中创建PhoneBookEntry

答案 2 :(得分:0)

为什么不创建一个电话簿,在那里有电话簿条目的数组列表,然后只是在电话簿中添加条目?