繁体   English   中英

如何将元素添加到数组列表中?

[英]How do I add my elements to my 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在库类而不是Student类中而导致工作不正常吗?

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

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

您的代码有两个问题:

  1. main是一个static方法,意味着它在任何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构造函数看起来像是向后分配的。

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

Library myLibrary = new Library();
myLibrary.add(new Student("John Elway", "je223", "j@gmail.com"));
// ... etc...
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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM