有没有什么办法排序java中的对象的arraylist没有使用比较器或类似的,我有学生类如下所示我需要根据他们的年龄排序学生对象,是否可以排序?不使用实施比较或类似的有没有什么办法排序java中的对象的arraylist没有使用比较器或可比较?
//Class of Students
//comparable or comparator Not implemented
public class Student {
private String studentname;
private int rollno;
private int studentage;
public Student(int rollno, String studentname, int studentage) {
this.rollno = rollno;
this.studentname = studentname;
this.studentage = studentage;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public int getStudentage() {
return studentage;
}
public void setStudentage(int studentage) {
this.studentage = studentage;
}
}
import java.util.*;
public class ArrayListSorting {
public static void main(String args[]){
//Array of Student Objects
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student(223, "Chaitanya", 26));
arraylist.add(new Student(245, "Rahul", 24));
arraylist.add(new Student(209, "Ajeet", 32));
Collections.sort(arraylist);
for(Student str: arraylist){
System.out.println(str.getStudentage());
}
}
}
你可以使用lambda函数?这是使用比较器,但不写许多代码。 'Collections.sort(list,(s1,s2) - > s1.getStudentage()。compareTo(s2。getStudentage));' 您不希望使用比较器的具体原因是什么? – zstring
不,它是不可能的,除非你自己编程算法 –
你确定'System.out.println(str);'语句有效吗?我不知道'println()'函数需要使用'java.lang.Object'类型的参数。 – progyammer