今天又碰到一个新BUG,记下来。
一直报空指针异常,我就很奇怪了,怎么就空指针了呢,我输出时,也能输出东西呀。
原来Arrays.sort() 和 Collections.sort() 都是对整个数组或者链表进行排序的,也就是整个数组或者链表有多长就会进行多长的排序。
而我new的数组时30,而真正new的对象只有20个,故后10个对象没有实例化,而排序比较时有用到,故会报空指针异常。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static <T> void main(String[] args) {
Scanner cin = new Scanner(System.in);
// 对象链表排序
List<People> list = new ArrayList<People>();
for(int i = 0; i < 20; i++) {
list.add(new People(20 - i, "ys" + i));
}
Collections.sort(list, new Comparator<People>() {
@Override
public int compare(People arg0, People arg1) {
// TODO Auto-generated method stub
return arg0.age - arg1.age;
}
});
for(int i = 0; i < 20; i++) {
System.out.println(list.get(i).age + list.get(i).name);
}
// 对象数组排序
People[] peos = new People[20];
for(int i = 0; i < 20; i++) {
peos[i] = new People(20 - i, "; song-" + i);
}
Arrays.sort(peos, new Comparator<People>() {
@Override
public int compare(People o1, People o2) {
// TODO Auto-generated method stub
System.out.println(o1.name);
return o1.age - o2.age;
}
});
System.out.println("===================");
for(int i = 0; i < 20; i++) {
System.out.println(peos[i].age + peos[i].name);
}
}
}
class People{
int age;
String name;
People(int age, String name){
this.age = age;
this.name = name;
}
}