如何在链表节点中保存对象?

kcwpcxri  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(343)

我有一个项目和项目想要一个学生管理系统。我开始做了。每个学生必须有3个属性(身份证、姓名、姓氏),我必须在链表中保留一个节点。如何在一个节点中保留这3个属性,以及如何建立连接?

hrirmatl

hrirmatl1#

了解java中的继承和泛型。你可以这样做:

List<Student> students = new LinkedList<>();
students.add(new Student(1, "name1", "surname1"));
students.add(new Student(2, "name2", "surname2")); 
students.add(new Student(3, "name3", "surname3"));

然后像这样打印出来:

for (Student student : students) {
    System.out.println(student);
}

学生班级:

public static class Student {
        private long id;
        private String name;
        private String surname;

        public Student(long id, String name, String surname) {
            this.id = id;
            this.name = name;
            this.surname = surname;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", surname='" + surname + '\'' +
                    '}';
        }
    }

相关问题