如何将我的元素添加到我的arraylist?

时间:2013-09-25 01:31:04

标签: java arraylist

public class Student {
    private String name;
    private String id;
    private String email;
    private  ArrayList<Student> s;

    public Student( String n, String i, String e)
    {
        n = name; i= id; e = email;
    }
}


public class Library {

    private  ArrayList<Student> s;

    public void addStudent(Student a)
    {
        s.add(a);
    }


    public static void main(String[] args)
    {
        Student g = new Student("John Elway", "je223", "j@gmail.com");
        Student f = new Student("Emily Harris", "emmy65", "e@yahoo.com");
        Student t = new Student("Sam Knight", "joookok", "fgdfgd@yahoo.com");

        s.addStudent(g);
        s.addStudent(f);
        s.addStudent(t);
    }

}

似乎我的学生对象会被添加到学生的arraylist中,但它不会那样工作。是不是因为arraylist在库类而不是Student类?

4 个答案:

答案 0 :(得分:3)

不应该是这样的构造函数吗?

public Student( String n, String i, String e)
{
    name = n; id = i; email = e;
}

答案 1 :(得分:3)

您的代码存在一些问题:

  1. mainstatic方法,意味着它在Library的任何实例的上下文之外执行。但是,sLibrary的实例字段。您应该s static字段或创建Library的实例并通过该实例引用该字段:

    public static void main(String[] args) {
        Library lib = new Library();
        . . .
        lib.addStudent(g);
        // etc.
    }
    
  2. addStudent不是ArrayList的成员函数;它是Library的成员函数。因此,您不应该编码s.addStudent(f);

  3. 您没有初始化s,因此当您的代码第一次尝试添加元素时,您将获得NullPointerException。你应该内联初始化它:

    private  ArrayList<Student> s = new ArrayList<Student>();
    

    或为Library编写构造函数并在那里初始化字段。

  4. 您向private ArrayList<Student> s;课程添加Student的最新更改是错误的。您最终会为您创建的每个学生单独列出学生名单;肯定不是你想要的!学生列表属于Library所在的位置。

  5. Student的构造函数看起来像是向后分配。

答案 2 :(得分:2)

您尝试从静态方法直接添加到实例ArrayList,这是您无法做到的事情,更重要的是,您不应该做。您需要首先在main方法中创建一个库实例,然后才能调用其中的方法。

Library myLibrary = new Library();
myLibrary.add(new Student("John Elway", "je223", "j@gmail.com"));
// ... etc...

答案 3 :(得分:1)

public class Library {

private  ArrayList<Student> s = new ArrayList<Student>(); //you forgot to create ArrayList

public void addStudent(Student a)
{
    s.add(a);
}


public static void main(String[] args)
{
    Student g = new Student("John Elway", "je223", "j@gmail.com");
    Student f = new Student("Emily Harris", "emmy65", "e@yahoo.com");
    Student t = new Student("Sam Knight", "joookok", "fgdfgd@yahoo.com");
    Library  library = new Library ();
    library.addStudent(g);
    library.addStudent(f);
    library.addStudent(t);
}

并像这样更改你的构造函数

public Student( String n, String i, String e)
{
        this.name = n;
        this.id = i; 
        this.email = e;
}