我是 Java 新手,我正在尝试了解比较器接口。我尝试了以下代码:
package comparator;
import java.io.*;
import java.util.*;
public class comparator {
public static void main(String args[]){
bankAccount[] ba=new bankAccount[500];
ba[0]=new bankAccount(50);
ba[1]=new bankAccount(90);
ba[2]=new bankAccount(20);
Comparator c=new comparing();
System.out.println(c.compare(ba[0], ba[1]));
Arrays.sort(ba, c);
}
}
class bankAccount{
public bankAccount(double bal){
balance=bal;
}
public double balance;
}
class comparing implements Comparator{
public int compare(Object first, Object second){
bankAccount ba1=(bankAccount)first;
bankAccount ba2=(bankAccount)second;
int retval;
if(ba1.balance<ba2.balance){
retval=-1;
}
else if(ba1.balance>ba2.balance){
retval=1;
}
else{
retval=0;
}
return retval;
}
}
我收到以下错误消息:
Exception in thread "main" java.lang.NullPointerException
at comparator.comparing.compare(comparator.java:29)
at java.util.TimSort.binarySort(TimSort.java:265)
at java.util.TimSort.sort(TimSort.java:208)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at comparator.comparator.main(comparator.java:13)
我能知道错误是什么吗。我应该如何使用 Arrays.sort() 方法。任何帮助将不胜感激。