gpt4 book ai didi

java - ArrayList 类型未定义方法 addFriend(Person)

转载 作者:行者123 更新时间:2023-12-05 01:55:59 27 4
gpt4 key购买 nike

我有 3 个 java 源文件。

  • Person.java
  • FriendsList.java
  • MyFriends.java

FriendsList包含 Person 类型对象的数组列表以及将新 friend 添加到列表的方法。

public class FriendsList{
ArrayList<Person> friendsList = new ArrayList<Person>(100);
// Constructor declaration of class
public FriendsList(ArrayList<Person> friendsList){
super();
this.friendsList = friendsList;
}
...
public void addFriend(Person friend){
friendsList.add(friend);
}
...
}

现在,在 MyFriends.java我创建了一个类型为 Person 的对象的新数组列表, 我声明了一个新的 Person我正在尝试使用 addFriend(Person) 方法将其添加到列表中但我收到错误 "Method addFriend(Person) is undefined for the type ArrayList<Person>"

public class MyFriends{
public void main(String[] args){
ArrayList<Person> friendsList = new ArrayList<Person>(100);
Person f1 = new Person("Alice", "Anderson", "519-472-4910", "02", "19");
friendsList.addFriend(f1);
}
}

我尝试了 FriendsList.java 中定义的所有其他方法但我收到相同的错误消息。我知道如果源文件在同一个文件夹中,则使用另一个文件中的方法的语法是 objectName.method(a) .

我做错了什么?

(对不起,如果我问的不对,这是我的第一个问题)

最佳答案

我猜您想改为执行以下操作:

public class MyFriends{
public void main(String[] args){
FriendsList friendsList = new FriendsList();
Person f1 = new Person("Alice", "Anderson", "519-472-4910", "02", "19");
friendsList.addFriend(f1);
}
}

你正在实例化一个 ArrayList<Person>但你真正想要的是创建一个你自己的对象 FriendsList类。


您的 FriendsList 中似乎没有无参数构造函数,因此您需要执行以下操作(实例化 ListPerson ):

public class MyFriends{
public void main(String[] args){
FriendsList friendsList = new FriendsList(new ArrayList<Person>(100));
Person f1 = new Person("Alice", "Anderson", "519-472-4910", "02", "19");
friendsList.addFriend(f1);
}
}

不过,在我看来,您应该考虑向 FriendsList 添加一个无参数构造函数。如下所示,以便我的第一个建议真正起作用(感谢@DavidConrad 的提示):

public class FriendsList{
ArrayList<Person> friendsList = new ArrayList<Person>(100);
// Constructor declaration of class
public FriendsList() {
}

public FriendsList(ArrayList<Person> friendsList){
this.friendsList.addAll(friendsList);
}
...
public void addFriend(Person friend){
friendsList.add(friend);
}
...
}

关于java - ArrayList<Person> 类型未定义方法 addFriend(Person),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69981219/

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