java创建一个学生类student,里面包括id,name,sex,age,将所有学生信息放入一个数组中,并实现增加,删除学生,按照姓名排序的功能
时间: 2023-05-23 13:02:27 浏览: 214
可以通过以下代码创建一个学生类 `Student`:
```
public class Student {
private int id;
private String name;
private String sex;
private int age;
public Student(int id, String name, String sex, int age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setAge(int age) {
this.age = age;
}
}
```
然后,可以使用以下代码将学生信息放入数组中:
```
List<Student> students = new ArrayList<>();
// add students
students.add(new Student(1, "Tom", "Male", 18));
students.add(new Student(2, "Lisa", "Female", 17));
students.add(new Student(3, "Lucy", "Female", 19));
```
为了实现增加学生的功能,你可以使用 `add` 方法,例如:
```
students.add(new Student(4, "David", "Male", 20));
```
删除学生可以使用 `remove` 方法,例如:
```
Student studentToRemove = students.get(0); // remove the first student
students.remove(studentToRemove);
```
按照姓名排序可以使用 `Collections.sort()` 方法,例如:
```
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student student1, Student student2) {
return student1.getName().compareTo(student2.getName());
}
});
```
这样,`students` 数组就按照姓名排序了。
阅读全文