日期:2014-05-20  浏览次数:20875 次

comparable排序乱码求教大神





import java.util.Arrays;







class BankAccount implements Comparable<Object>{


public int account;
public Integer saved;
public String name;
BankAccount(String name,int account,Integer saved){

this.name=name;

this.account=account;

this.saved=saved;

}


public int compareTo(Object o){

if (o instanceof BankAccount){
if(saved>((BankAccount)o).saved)
{return 1;
 
}else if(saved<((BankAccount)o).saved){
return -1;
}else{
return 0; 
}
}else{
//非TestComparable对象与之比较,则抛出异常
throw new ClassCastException("Can't compare");
}

 



}
}




public class come {





public static void main(String[] args) {
// TODO Auto-generated method stub
 
BankAccount[] asd = new BankAccount[3];
asd[0]= new BankAccount("zou",1233,6000000);
asd[1]= new BankAccount("zou",6435,7000000);
asd[2]= new BankAccount("zou",3737,5000000);
 
 
//排序前


System.out.println(Arrays.asList(asd));

//排序

Arrays.sort(asd);

//排序后

for(BankAccount b : asd)
{
System.out.println(b);
}




}

}

------解决方案--------------------
首先排序结果其实是正确的,按照saved做升序处理
其次你说的排序乱码,是应为你
Java code

for(BankAccount b : asd)
{
System.out.println(b);
}