将对象添加到数组列表.尝试将对象添加到 ArrayList 时出错 [英] Add Object to array list. Get error when try add obect to ArrayList

查看:63
本文介绍了将对象添加到数组列表.尝试将对象添加到 ArrayList 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以回答为什么我的数组列表有问题.我有一个类:ListPeopleMain(用于运行所有内容).

Could somebody answer why there is a problem with my array list. I have a classes: List, People and Main (to run everything).

List 中,我创建了一个新的ArrayList 来保存People 类型的对象.

In List I am creating a new ArrayList to hold objects of type People.

Main 我正在创建新的 List 对象,然后创建新的 People 对象,然后从 List 对象调用 add 方法,此时我得到一个 nullPointerException 异常.

In Main I am making new List object, then make new People object and then calling from List object add method, and at this point I get a nullPointerException exception.

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

这篇关于将对象添加到数组列表.尝试将对象添加到 ArrayList 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆