使用属性在arraylist中创建新对象

时间:2013-03-13 04:50:15

标签: java arraylist

我是Java新手,我开始使用ArrayLists。我要做的是为学生创建一个ArrayList。每个学生都有不同的属性(name, id)。我试图弄清楚如何添加具有此属性的新学生对象。这就是我所拥有的:

ArrayList < Student > studentArray;
public Student(String name, int id) {
  this.fname = name;
  this.stId = id;
}
public Stromg getName() {
  return fname;
}
public int getId() {
  return stId;
}
public boolean setName(String name) {
  this.fname = name;
  return true;
}
public boolean setIdNum(int id) {
  this.stId = id;
  return true;
}

3 个答案:

答案 0 :(得分:6)

您需要的是以下内容:

import java.util.*;

class TestStudent
{
    public static void main(String args[])
    {
        List<Student> StudentList= new ArrayList<Student>();
        Student tempStudent = new Student();
        tempStudent.setName("Rey");
        tempStudent.setIdNum(619);
        StudentList.add(tempStudent);
        System.out.println(StudentList.get(0).getName()+", "+StudentList.get(0).getId());
    }
}

class Student
{
    private String fname;
    private int stId;

    public String getName()
    {
        return this.fname;
    }

    public int getId()
    {
        return this.stId;
    }

    public boolean setName(String name)
    {
        this.fname = name;
        return true;
    }

    public boolean setIdNum(int id)
    {
        this.stId = id;
        return true;
    }
}

答案 1 :(得分:2)

通过将适当的值传递给构造函数来实例化Student对象。

Student s = new Student("Mr. Big", 31);

您可以使用ArrayList运算符将元素放入List(或.add())。 *

List<Student> studentList = new ArrayList<Student>();
studentList.add(s);

您可以使用绑定到Scanner的{​​{1}}来检索用户输入。

System.in

你用循环重复一遍。该部分应作为练习留给读者。

*:还有其他选项,但Scanner scan = new Scanner(System.in); System.out.println("What is the student's name?"); String name = scan.nextLine(); System.out.println("What is their ID?"); int id = scan.nextInt(); 只是将其添加到最后,这通常是您想要的。

答案 2 :(得分:1)

final List<Student> students = new ArrayList<Student>();
students.add(new Student("Somename", 1));

......等等添加更多学生

相关问题