create new object in arraylist with attributes

前端 未结 3 902

I am new to Java and I am starting to work with ArrayLists. What I am trying to do is create an ArrayList for students. Each student has differen

相关标签:
3条回答
  • 2021-01-07 11:10
    final List<Student> students = new ArrayList<Student>();
    students.add(new Student("Somename", 1));
    

    ... and so on add more students

    0 讨论(0)
  • 2021-01-07 11:12

    You instantiate a Student object by passing the appropriate values to the constructor.

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

    You place elements into an ArrayList (or List) by using the .add() operator.*

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

    You retrieve user input via the use of a Scanner bound to 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();
    

    You repeat this with a loop. That portion shall be left as an exercise to the reader.

    *: There are other options, but add() simply adds it to the end, which is typically what you want.

    0 讨论(0)
  • 2021-01-07 11:25

    What you need is something like the following:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题