Collections.sort(list, this::compare);和Collections.sort(list, new Student());有什么区别
时间: 2024-05-31 09:10:45 浏览: 21
`Collections.sort(list, this::compare)`和`Collections.sort(list, new Student())`的区别在于传入的第二个参数不同。
`Collections.sort(list, this::compare)`中的第二个参数是一个方法引用,即使用当前类中的`compare`方法进行比较。这种方式适用于当前类已经实现了`Comparator`接口,且需要使用该类中已经实现的比较方法进行排序的情况。
而`Collections.sort(list, new Student())`中的第二个参数是一个新创建的`Student`对象,即使用该对象中的比较方法进行比较。这种方式适用于需要自定义比较方法,或者当前类没有实现`Comparator`接口的情况。
综上所述,`Collections.sort(list, this::compare)`适用于已经实现了`Comparator`接口且想要使用该类中已经实现的比较方法进行排序的情况,`Collections.sort(list, new Student())`适用于需要自定义比较方法或者当前类没有实现`Comparator`接口的情况。
相关问题
public void sortById() { Collections.sort(stu, new Comparator<student>() { @Override public int compare(student o1, student o2) { return o1.getId().compareTo(o2.getId()); }
这段代码是一个方法,作用是对一个名为stu的List<student>对象中的元素按照学生ID进行排序。具体来说,它使用了Java中的Collections.sort()方法,并传入了一个实现了Comparator接口的匿名内部类对象作为参数,用于指定排序规则。
在匿名内部类中,重写了Comparator接口中的compare()方法,该方法接收两个student对象o1和o2作为参数,比较它们的ID属性,返回一个整数值,表示它们的大小关系。如果o1的ID小于o2的ID,则返回一个负数;如果o1的ID等于o2的ID,则返回0;如果o1的ID大于o2的ID,则返回一个正数。
最终,调用Collections.sort()方法会通过比较List中各个元素的ID属性,按照从小到大的顺序对它们进行排序。排序后的结果会直接影响原本的List对象,因此不需要返回任何值。
Arrays.sort()两个对象list根据关键字排序
如果你有一个包含对象的List,并希望根据对象的某个关键字进行排序,你可以使用Collections.sort()方法和Comparator接口来实现。
假设你有一个Student类,其中包含name和age两个属性。你可以按照以下方式定义一个Comparator来根据年龄对Student对象进行排序:
```
public class StudentAgeComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge();
}
}
```
然后你可以使用Collections.sort()方法并传入该Comparator来对List进行排序:
```
List<Student> studentList = new ArrayList<>();
// 添加Student对象到List中
Collections.sort(studentList, new StudentAgeComparator());
```
如果你想按照姓名进行排序,只需定义另一个Comparator并将其传递给Collections.sort()方法即可。