微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将对象添加到数组列表尝试将对象添加到ArrayList时出错

如何解决将对象添加到数组列表尝试将对象添加到ArrayList时出错

| 有人可以回答为什么我的数组列表有问题。我有一个类:
List
People
Main
(运行所有内容)。 在
List
中,我将创建一个新的
ArrayList
来容纳
People
类型的对象。 在
Main
中,我将创建一个新的List对象,然后再创建一个新的People对象,然后从List对象的
add
方法中进行调用,这时我得到了
nullPointerException
异常。
public class Main {
    public static void main(String[] args) {

        List l = new List();       // making new List object 
        People p = new People();   // making new People object

        l.addPeople(p);           // calling from List object \"addPeople\" method and
    }            

                 // parsing People object \"p\"
 }




import java.util.ArrayList;

public class List {

        public List(){           //constructor
    }

        ArrayList<People>list;      // new ArrayList to hold objects of type \"People\"

    public void addPeople(People people){   
        list.add(people);               // I get error here
    }
} 

public class People {

    public People(){         // constructor
    }
}
    

解决方法

在构造函数中:
list = new ArrayList<People>();
    ,您没有在任何时候实例化该列表。在您的构造函数中执行以下操作:
   public List(){           //constructor
          list = new ArrayList<People>();
   }
    ,我不确定这是否相关,但是将您的类命名为“ List \”不是一个好主意,因为这会隐藏List接口。     ,您需要在
list
字段中放入
ArrayList
实例。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。