I want to sort an ArrayList
of objects by the length of the vector objects.
double[] s ={1,2,3,4};
double[] s2 ={1,2};
double[] s3 ={1,2,3};
Student[] Facultate ={new Student(s),new Student(s2)};
ArrayList<Student> FacultateList = new ArrayList<Student>(Arrays.asList(Facultate));
I want FacultateList
to be ordered like s2,s3,s
.
Use Collections.sort
with a custom comparator:
Collections.sort(facultateList, new Comparator<Student>() {
public int compare(Student a, Student b) {
return a.getLength().compareTo(b.getLength());
}
});
Alternatively, if this is the default way to sort students, make Student
implement Comparable<Student>
, implement the appropriate compareTo
method in the class itself, and use Collections.sort
without the custom comparator.
(Just an aside that will save you confusion later, the convention in Java is that variables start with a lowercase letter, so facultateList
, not FacultateList
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.