简体   繁体   中英

ArrayList.add() not adding to ArrayList

I am trying to add some names and phone numbers created from the constructor of the PhoneBookEntry class, store them inside of an ArrayList inside of the PhoneBook class, and then be able to print out the array list.

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));
    }
}
}

Current output:

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

It's because you create a new PhoneBook for each PhoneBookEntry , ending up with five lists with one entry each.

Your code should probably look more like

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

You are creating a new PhoneBook with every PhoneBookEntry .

Make PhoneBook book a field:

public PhoneBook book = new PhoneBook();

and simply add each new entry into it with every new PhoneBookEntry object. Or simply create your PhoneBook book in the main.

为什么不创建一个电话簿,在其中创建电话簿条目的数组列表,然后仅将条目添加到电话簿中?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM