我实现了一个比较器类,在我的例子中对一组对象或“Persons”进行排序。但是,似乎有一些错误,所以当我单击GUI的下一个按钮时,我收到以下错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at RectangleProgram$CustomComparator.compare(RectangleProgram.java:30)
at RectangleProgram$CustomComparator.compare(RectangleProgram.java:26)
at java.util.TimSort.binarySort(TimSort.java:265)
at java.util.TimSort.sort(TimSort.java:208)
以下是相关代码的片段:
public class Person//HERE IS THE OBJECT THE COMPARATOR IS REFERRING TO
{
String firstname; String lastname; int z;
public Person(String l, String m, int e)
{
firstname=l; lastname=m; z=e;
}
public String getFirstName()
{
return firstname;
}
}
public class CustomComparator implements Comparator<Person> { // COMPARATOR BEGINS HERE
@Override
public int compare(Person object1, Person object2)
{
return object1.getFirstName().compareTo(object2.getFirstName());
}
} // COMPARATOR ENDS HERE
public static Person [] arr=new Person [100]; // ARRAY TO BE SORTED
// class implementing the sort
public class re implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
if (counter==0)
{
getData();
Arrays.sort(arr, new CustomComparator());
}
}
}
有人能告诉我代码有什么问题,并导致错误吗?注意,它不是编译错误,只是单击下一个按钮[其中类re是动作侦听器]不会使它执行任何操作。
答案 0 :(得分:2)
我在Java 8
代码:
List<Person> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Person p = new Person(Integer.toString(i), Integer.toString(i), i);
list.add(p);
}
Collections.shuffle(list);
System.out.println("the shuffled list");
list.forEach(i -> System.out.println(i.toString() + " "));
Collections.sort(list, (p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()));
System.out.println("------------------------ \n the orderd list");
list.forEach(i -> System.out.println(i.toString() + " "));
输出:
the shuffled list
0 0 0
9 9 9
8 8 8
7 7 7
3 3 3
6 6 6
2 2 2
4 4 4
1 1 1
5 5 5
------------------------
the orderd list
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
让我知道发生了什么或者您需要任何解释