parent
11e0e3ff01
commit
729101d055
@ -0,0 +1,59 @@
|
||||
package com.never.basic;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
public class ComparatorDemo {
|
||||
public static void main(String[] args) {
|
||||
Student s1 = new Student(4, 17, "张三");
|
||||
Student s2 = new Student(1, 17, "张三");
|
||||
Student s3 = new Student(3, 17, "张三");
|
||||
Student s4 = new Student(8, 17, "张三");
|
||||
Student s5 = new Student(6, 17, "张三");
|
||||
System.out.println("--------Array------------");
|
||||
Student[] arr = {s1,s2,s3,s4,s5};
|
||||
for(int i = 0 ;i <arr.length; i++){
|
||||
System.out.println(arr[i]);
|
||||
}
|
||||
System.out.println("--------------------");
|
||||
Arrays.sort(arr,new IdComparator());
|
||||
for(int i = 0 ;i <arr.length; i++){
|
||||
System.out.println(arr[i]);
|
||||
}
|
||||
|
||||
System.out.println("------ArrayList-------------");
|
||||
ArrayList<Student> list = new ArrayList<>();
|
||||
list.add(s1);
|
||||
list.add(s2);
|
||||
list.add(s3);
|
||||
list.add(s4);
|
||||
list.add(s5);
|
||||
for(Student s: list){
|
||||
System.out.println(s);
|
||||
}
|
||||
System.out.println("--------------------");
|
||||
list.sort(new IdComparator());
|
||||
for(Student s: list){
|
||||
System.out.println(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
class IdComparator implements Comparator<Student>{
|
||||
|
||||
|
||||
@Override
|
||||
public int compare(Student o1, Student o2) {
|
||||
int res = 0;
|
||||
|
||||
if(o1.getId()<o2.getId()){
|
||||
res = -1;
|
||||
}else if (o1.getId()>o2.getId()){
|
||||
res = 1;
|
||||
}
|
||||
else if (o1.getId() == o2.getId()){
|
||||
res = 0;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.never.basic;
|
||||
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class Student {
|
||||
private Integer id;
|
||||
private Integer age;
|
||||
private String name;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Student{" +
|
||||
"id=" + id +
|
||||
", age=" + age +
|
||||
", name='" + name + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading…
Reference in new issue