添加对象数组列表。获取错误,当试图添加到obect ArrayList的 [英] Add Object to array list. Get error when try add obect to ArrayList

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

问题描述

有人能回答,为什么有我的数组列表的一个问题。我有一个类:列表(运行一切)。

列表我创建一个新的的ArrayList 来保存类型为人物对象

我想提出新的List对象,然后进行新的人反对,然后从列表对象调用添加方法,在这一点上,我收到了 NullPointerException异常例外。

 公共类主要{
    公共静态无效的主要(字串[] args){        列表L =新名单(); //作出新的列表对象
        人们P =新的人物(); //作出新的人反对        l.addPeople(P); //从列表对象调用addPeople的方法和
    }                 //解析人反对P
 }
进口的java.util.ArrayList;公共类列表{        公开名单(){//构造
    }        ArrayList的<人与GT;清单; //新的ArrayList来保存类型为人的对象    公共无效addPeople(人民的人){
        list.add(人); //我得到的错误在这里
    }
}公共类人{    公众人物(){//构造
    }
}


解决方案

在构造函数中:

 列表=新的ArrayList<人与GT;();

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

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

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
    }
}

解决方案

In the constructor:

list = new ArrayList<People>();

这篇关于添加对象数组列表。获取错误,当试图添加到obect ArrayList的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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