一:Arrays.sort(int[] a )
二:Collections.sort(List)
Collections.reverse(list);
public class Test1 {
public static void main(String[] args) {
List<Dog> list = new ArrayList<Dog>();
list.add(new Dog(1));
list.add(new Dog(3));
list.add(new Dog(4));
list.add(new Dog(2));
list.add(new Dog(5));
list.add(new Dog(6));
Collections.sort(list);
for(Dog dog : list){
System.out.println(dog.getAge());
}
List<String> list = new ArrayList<String>();
list.add("a");
list.add("c");
list.add("b");
Collections.sort(list);
for(String s : list){
System.out.println(s);
}
}
}
public class Dog implements Comparable {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Dog(){}
public Dog( int age){
this.age = age;
}
@Override
public int compareTo(Object o) {
Dog dog = (Dog)o;
if( null == o){
return -2;
}
if(this.getAge() > dog.getAge()){
return 1;
}else if( this.getAge() == dog.getAge()){
return 0;
}
return -1;
}
}
二:Collections.sort(List)
Collections.reverse(list);
public class Test1 {
public static void main(String[] args) {
List<Dog> list = new ArrayList<Dog>();
list.add(new Dog(1));
list.add(new Dog(3));
list.add(new Dog(4));
list.add(new Dog(2));
list.add(new Dog(5));
list.add(new Dog(6));
Collections.sort(list);
for(Dog dog : list){
System.out.println(dog.getAge());
}
List<String> list = new ArrayList<String>();
list.add("a");
list.add("c");
list.add("b");
Collections.sort(list);
for(String s : list){
System.out.println(s);
}
}
}
public class Dog implements Comparable {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Dog(){}
public Dog( int age){
this.age = age;
}
@Override
public int compareTo(Object o) {
Dog dog = (Dog)o;
if( null == o){
return -2;
}
if(this.getAge() > dog.getAge()){
return 1;
}else if( this.getAge() == dog.getAge()){
return 0;
}
return -1;
}
}