在根据名称对名称和年龄作为属性的Customer Class(用户定义)的arraylist进行排序时,Collections.sort()方法显示错误“java.util.Comparator类型未解析。它是间接引用所需的.class文件。
package comparable;
import java.util.*;
public class Tester {
public static void main(String[] args){
List<Customer> custtlist=new ArrayList<Customer>();
Customer c1=new Customer("vikas",1);
Customer c2=new Customer("mittal",2);
custtlist.add(c1);
custtlist.add(c2);
System.out.println("Before Sorting");
Iterator<Customer> iterator = custtlist.iterator();
while(iterator.hasNext()){
Customer customer = (Customer) iterator.next();
System.out.println(customer.getCustname());
}
Collections.sort(custtlist);
System.out.println("After Sorting");
iterator = custList.iterator();
while (iterator.hasNext()) {
Customer customer = (Customer) iterator.next();
System.out.println(customer.getCustName());
}
}
}
//Customer Class
package comparable;
public class Customer implements Comparable<Customer> {
private String custname;
private int age;
public Customer(String custname, int age) {
this.custname = custname;
this.age = age;
}
public Customer() {
}
public String getCustname() {
return custname;
}
public void setCustname(String custname) {
this.custname = custname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Customer c){
return this.custname.compareTo(c.getCustname());
}
}
答案 0 :(得分:2)
你的代码中有很多错别字。在我纠正它们之后,编译成功了。我冒昧地做了一些改进和造型。
import java.util.*;
public class Tester {
public static void main(String[] args){
List<Customer> customersList = new ArrayList<Customer>();
Customer c1 = new Customer("vikas", 1);
Customer c2 = new Customer("mittal", 2);
customersList.add(c1);
customersList.add(c2);
System.out.println("Before Sorting");
for(Customer customer : customersList) {
System.out.println(customer.getName());
}
Collections.sort(customersList);
System.out.println("\nAfter Sorting");
for(Customer customer : customersList) {
System.out.println(customer.getName());
}
}
}
public class Customer implements Comparable<Customer> {
private String name;
private int age;
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
public Customer() {
}
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 int compareTo(Customer c){
return this.name.compareTo(c.getName());
}
}