gpt4 book ai didi

java - ArrayList.add() 不添加到 ArrayList

转载 作者:行者123 更新时间:2023-12-01 18:05:54 25 4
gpt4 key购买 nike

我试图添加一些从 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

最佳答案

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

您的代码可能看起来更像

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

关于java - ArrayList.add() 不添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36464548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com