Java Comparator接口 代码演示
演示1.
package Practice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Comparator {
public static void main(String[] args) {
List<Integer> nums=new ArrayList<Integer>();
nums.add(1);
nums.add(3);
nums.add(2);
Collections.sort(nums, new java.util.Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
System.out.println(nums);
}
}
演示2
package Practice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Comparator {
public static void main(String[] args) {
List<String> names=new ArrayList<String>();
names.add("james");
names.add("Tom");
names.add("Mike");
names.add("Peter");
names.add("LinDan");
names.add("admin");
names.add("aamin");
Collections.sort(names,new MyComparator());
System.out.println(names);
}
}
class MyComparator implements java.util.Comparator<String>{
@Override
public int compare(String o1, String o2) {
if (o1.length()!=o2.length())
return o1.length()-o2.length();
return o1.compareTo(o2);
}
}