Java 类数组的字母顺序
我有一个ClassJava 类数组的字母顺序,java,sorting,java-7,bubble-sort,Java,Sorting,Java 7,Bubble Sort,我有一个ClassCustomer数组。我想根据名为name的字段,按字母顺序对ClassCustomer数组中的元素重新排序 以下是我正在使用的代码: int j; boolean flag = true; // will determine when the sort is finished Customer temp; while ( flag ) { flag = false;
Customer
数组。我想根据名为name
的字段,按字母顺序对ClassCustomer
数组中的元素重新排序
以下是我正在使用的代码:
int j;
boolean flag = true; // will determine when the sort is finished
Customer temp;
while ( flag )
{
flag = false;
for ( j = 0; j < count_customers; j++ )
{
if ( customers[ j ].getName().toString().compareToIgnoreCase( customers[ j + 1 ].getName().toString() ) > 0 )
{
temp = customers[ j ];
customers[ j ] = customers[ j+1 ]; // swapping
customers[ j+1 ] = temp;
flag = true;
}
}
}
.toString()
是在Customer
类中定义的,它只是将客户的所有信息打印出来
那么我做错了什么 创建一个新类
CustomerComparator
并使用array对Customer[]进行排序。排序(array,new CustomerComparator())代码>
公共类CustomerComparator实现Comparator{
@凌驾
公共整数比较(客户c1、客户c2){
返回c1.getName().compareTo(c2.getName());
}
}
创建一个新类CustomerComparator
并使用数组对Customer[]进行排序。排序(数组,new CustomerComparator())代码>
公共类CustomerComparator实现Comparator{
@凌驾
公共整数比较(客户c1、客户c2){
返回c1.getName().compareTo(c2.getName());
}
}
<代码> >您如何设置CurtTuCuffs的值?<代码> CurtTuffux/Cuth>正在工作,我只是在添加新客户时运行<代码> CurtTuffux++/Cuth>(不相关,但考虑给您的标志一个有意义的名称)。不是一个严格的方法,你设定了顾客的价值吗?<代码> CurtTuffux/Cuth>正在工作,我只是在添加一个新客户的时候运行<代码> CurtTuffux++/Cuth>(不相关,但是考虑给你的标志一个有意义的名字)。@ Aya'AgAMAL,我不能只打印客户[I],那是一个对象,不是一个ScRigor如果你不能改变客户,为它创建一个比较器。我不能编辑客户,如何创建比较器?您能解释一下吗?或者如果您不能更改客户,请为其创建一个比较器。我不能编辑客户,我如何才能创建比较器?你能解释一下吗?
for(int i=0; i < count_customers; i++)
{
tmp_results += customers[ i ].toString() + "\n";
}
public class CustomerComparator implements Comparator<Customer> {
@Override
public int compare(Customer c1, Customer c2) {
return c1.getName().compareTo(c2.getName());
}
}