我为商店制作算法。我制作了一个包含客户信息的数组。现在我想在这个数组上实现一个merge-sort并按年龄排序。这是我的客户类代码:
public class Customer{
private int customerID;
private String name;
private int age;
private char gender;
private String email;
public List<Customer> customerList = new ArrayList<Customer>();
public Customer(String name, int age, char gender, String email) {
this.customerID = customerList.size();
this.name= name;
this.age= age;
this.gender= gender;
this.email = email;
customerList.add(this);
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
这是我的合并排序:
private int[] helper;
private int number;
public void sort(Klant[] values) {
this.customerList= values; <---Error
number = values.length;
this.helper = new int[number];
mergesort(0, number - 1);
}
private void mergesort(int low, int high) {
// check if low is smaller then high, if not then the array is sorted
if (low < high) {
// Get the index of the element which is in the middle
int middle = low + (high - low) / 2;
// Sort the left side of the array
mergesort(low, middle);
// Sort the right side of the array
mergesort(middle + 1, high);
// Combine them both
merge(low, middle, high);
}
}
private void merge(int low, int middle, int high) {
// Copy both parts into the helper array
for (int i = low; i <= high; i++) {
helper[i] = customerList[i];
}
int i = low;
int j = middle + 1;
int k = low;
// Copy the smallest values from either the left or the right side back
// to the original array
while (i <= middle && j <= high) {
if (helper[i] <= helper[j]) {
customerList[k] = helper[i];
i++;
} else {
customerList[k] = helper[j];
j++;
}
k++;
}
// Copy the rest of the left side of the array into the target array
while (i <= middle) {
customerList[k] = helper[i];
k++;
i++;
}
}
在线: this.customerList = values;我收到错误:不兼容的类型Customer []无法转换为List
我的问题是我如何修复此错误,并且我的合并排序是否正确?
编辑1: @Jens 你的第一个选择: this.customerList = Arrays.asList(values);
修正了错误。但现在我在这一行上收到错误:
helper[i] = customerList[i];
它说:需要数组,但找到了列表
有人知道如何解决这个问题吗?
答案 0 :(得分:2)
您不能将数组分配给列表。
尝试
this.customerList= Arrays.asList(values);
或将方法参数更改为List<Customer>
public void sort(List<Customer> values) {
答案 1 :(得分:0)
为什么不使用Collections.sort()方法?它还使用合并排序算法。
List<Klant> list = Arrays.asList(values);
Collections.sort(list);
或者您也可以使用Arrays.sort(),但它不使用合并排序。
但请记住,您需要它来为Klant
课程实施Comparable界面。
更新:
如果您需要自己实施合并排序算法,可能需要将customerList
变量类型从List
更改为Customer[]
数组。如果您想使用列表,则可以Jens建议使用该列表,但使用List
的{{1}}方法,而不是通过=
分配值。