You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java调用addFriend报错提示ArrayList<Person>类型未定义该方法如何解决

问题原因

addFriend是你自定义在FriendsList类中的方法,不属于JDK自带的ArrayList类。你在代码中直接对ArrayList类型的friendsList对象调用该方法,自然会触发「方法未定义」的报错。你混淆了自定义的FriendsList封装类和内置ArrayList类的使用边界。

修正方案

你需要先实例化你自己实现的FriendsList类,再调用类中定义的相关方法,修正后的MyFriends类代码如下:

public class MyFriends{
    // main方法必须加static修饰,否则JVM无法识别程序入口
    public static void main(String[] args){
        ArrayList<Person> initFriends = new ArrayList<Person>(100);            
        Person f1 = new Person("Alice", "Anderson", "519-472-4910", "02", "19");
        // 实例化自定义的FriendsList对象
        FriendsList friendsOperator = new FriendsList(initFriends);
        // 调用FriendsList类中定义的addFriend方法
        friendsOperator.addFriend(f1);
    }
}
可选优化说明

如果不需要自定义初始的ArrayList对象,也可以给FriendsList新增无参构造,直接在类内部完成列表初始化,不需要外部传入:

public class FriendsList{
    ArrayList<Person> friendsList = new ArrayList<Person>(100);
    // 新增无参构造方法
    public FriendsList(){
    }   
    // 保留现有带参构造方法 
    public FriendsList(ArrayList<Person> friendsList){
            super();
            this.friendsList = friendsList;
    }    
    // 其余原有代码保持不变
    ...
}

优化后MyFriends类可以直接初始化FriendsList,无需手动创建ArrayList对象:

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

内容的提问来源于stack exchange,提问作者cruella devil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:06:03