用Java实现存储自定义对象并遍历Student(name,age),并按照姓名的长度排序
时间: 2024-02-01 11:16:05 浏览: 33
可以通过实现Comparable接口,在类中重写compareTo方法来实现按照姓名长度排序。具体实现步骤如下:
1.创建一个Student类,包含姓名和年龄属性,并实现Comparable接口。
```java
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student o) {
return this.name.length() - o.getName().length();
}
}
```
2.创建一个存储Student对象的ArrayList,并添加一些Student对象。
```java
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student("Tom", 18));
list.add(new Student("Jerry", 20));
list.add(new Student("Bob", 19));
list.add(new Student("Alice", 21));
}
}
```
3.使用Collections.sort方法将集合按照姓名长度排序。
```java
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student("Tom", 18));
list.add(new Student("Jerry", 20));
list.add(new Student("Bob", 19));
list.add(new Student("Alice", 21));
Collections.sort(list);
for (Student s : list) {
System.out.println(s.getName() + " " + s.getAge());
}
}
}
```
输出结果为:
```
Tom 18
Bob 19
Jerry 20
Alice 21
```
可以看到,输出结果按照姓名长度从短到长排序。