java - 比较对象数组中某个特定字段的值以进行合并排序。关于使用 compareTo 的初学者问题
问题描述
很简单,我们必须实现我们自己选择的排序功能来对客户数据库进行排序。客户从 excel 文件中导入并存储在数组中。我选择了 Mergesort 来提出一个涉及大 O 符号的不同问题。
这是数组的导入和创建
Scanner sc = new Scanner(new File("customers.csv")); Customer[] customers = new Customer[1000];
客户类看起来像这样 `
class Customer implements Comparable{
private int cusNo;
private String dateOfBirth;
private String firstName;
private String lastName;
//The constructor
public Customer(int cusNo, String dateOfBirth, String firstName, String lastName)
{
this.cusNo = cusNo;
this.dateOfBirth = dateOfBirth;
this.firstName = firstName;
this.lastName = lastName;
}
如标题中所述,我遇到的问题来自 mergsort 算法的合并方法中的比较部分。
Customer[] tempCus = new Customer[1000];
int c = 0;
while(i < mid && j < UpperB) {
if(customers.getFirstName[i].compareTo.(customers.getFirstName[b])<=0) {
tempCus[i] = Customer[i];
老实说,考虑到类的构造,我真的不知道如何在这种情况下使用 compareTo 方法,并且非常感谢解决方案/特定于上下文的解释,或者如果我走上了一条错误的道路,有点重定向。在经过多次不同的尝试以使 compareTo 的语法正确之后,我已经完成了我已经完成的操作。相当有信心 compareTo 是正确的选择,但实现超出了我的范围。我通常不确定如何在没有额外困难的方法和随附的括号 forrest 的情况下回调数组中的特定值。
给定任务,使用内置的 sort() 方法不是一个选项
解决方案
不要那样做,但要么Customer
实现Comparable<Customer>
并实现该方法compareTo(Customer other)
,要么使用 aComparator<Customer>
并实现该方法compare(Customer left, Customer right)
。实现与对象为this
andother
或left
and基本相同right
。然后依次比较相关元素,直到全部比较完或结果为 != 0。
获取比较器的简单方法是这样的:
Comparator<Customer> comparator = Comparator.comparing( Customer:: getFirstName).thenComparing( Customer::getLastName );
然后像这样使用它(重用你的代码,所以我没有检查它的正确性):
//assuming i and b are correct indices
if(comparator.compare(tempCus[i], tempCus[b])<=0) {
...
由于您想使用Comparable
这里的示例(考虑一下并根据需要进行扩展):
class Customer implements Comparable<Customer> {
public int compareTo(Customer other) {
//or: int result = this.firstName.compareTo(other.getFirstName());
int result = String.compare(this.firstName, other.getFirstName());
//0 means the strings are equal, otherwise we're done
if( result != 0 ) {
return result;
}
result = String.compare(this.lastName, other.getLastName());
//if needed add more comparisons here
return result;
}
}
然后就像使用它一样if(tempCus[i].compareTo(tempCus[b]) <= 0)
推荐阅读
- c++ - Apache Thrift 超时
- python - C++ last_write_time 与 Python 的比较
- javascript - 使用多个数组解析 JSON 并在 HTML 中显示结果
- javascript - 使用 initComplete 在 Shiny 应用程序中使用 Javascript 定位特定的 DT::datatable 表
- python - Python 程序有时会以“IndexError: string index out of range”退出,有时运行良好
- javascript - 续集多对多深层嵌套关联
- python - Pandas - 如何根据自定义日历计算两个日期的天数
- reactjs - 反应材料ui在左侧增长
- html - 在 CSS 中将元素包装在类名中时出错
- linux - 关闭 GCP vm 中的串行输出日志