我需要按名字和姓氏的顺序对对象数组进行排序。对象有4个字段:fName,lName,date和balance。我需要能够按名称的顺序对数组进行排序,但每次尝试时我都会发现我的输出与我最初将它们放入数组的顺序相匹配。我还需要实现Comparable接口,但每次尝试时都会收到错误消息,说我没有覆盖方法compareTo()。
这是我的代码:
public static int compareTo(Account a, Account b)
{
String nameOne = a.getLName();
String nameTwo = b.getLName();
String name1 = a.getFName();
String name2 = b.getFName();
if(nameOne.compareTo(nameTwo) == -1)
{
return -1;
}else if(nameOne.compareTo(nameTwo) == 1)
{
return 1;
}else if(nameOne.compareTo(nameTwo) == 0)
{
if(name1.compareTo(name2) == -1)
{
return -1;
}else
{
return 1;
}
}else{
return 1;
}
}
public static void main(String [] args)
{
int shortestStringIndex;
Account[] accounts = new Account[5];
Account[] sortedAccount = new Account[5];
accounts[0] = new Account("John", "Myers", "6/11/1994", 100);
accounts[1] = new Account("Bill", "Bane", "7/11/1994", 200);
accounts[2] = new Account("Marcus", "Bane", "9/7/1033", 891);
accounts[3] = new Account("Mike", "Rogers", "4/14/2014", 500);
accounts[4] = new Account("Bill", "Philip", "7/11/1996", 600);
for(int j=0; j < accounts.length - 1;j++)
{
shortestStringIndex = j;
for (int i=j+1 ; i<accounts.length; i++)
{
if(compareTo(accounts[i],accounts[shortestStringIndex])<0)
{
shortestStringIndex = i;
}
}
if(shortestStringIndex != j)
{
sortedAccount[0] = accounts[j];
accounts[j] = accounts[shortestStringIndex];
accounts[shortestStringIndex] = sortedAccount[0];
}
}
for(int i = 0; i<accounts.length; i++)
{
System.out.println(accounts[i].toString());
}
}
任何有关使Comparable接口实现或对其进行排序的帮助都将非常感激。谢谢。