I created this program. I'm trying to get it to sort my list, but it will not sort. I have included the main program as well as my Employee class.
t spits out this when I try to sort it:
sort(java.util.list) in Collections cannot be applied to (java.util.ArrayList )
Here is the error code I am given : no instance(s) of variable(s) T exist so that Employee
conforms to Comparable<? super T>
Comparable<? super T>
import java.util.*;
import java.lang.*;
public class Employee {
String name;
public Employee(String name) {
this.name = name;
}
// Used to print student details in main()
public String toString() {
return this.name;
}
}
public class Schedule {
public static void main (String args[] ) {
ArrayList<Employee> listOfEmployees = new ArrayList<Employee>();
listOfEmployees.add(new Employee("Lauren"));
listOfEmployees.add(new Employee("Greg"));
listOfEmployees.add(new Employee("Brenda"));
listOfEmployees.add(new Employee("Derek"));
listOfEmployees.add(new Employee("Brittany"));
System.out.println("Unsorted");
for (int i=0; i<listOfEmployees.size(); i++) {
System.out.println(listOfEmployees.get(i));
}
Collections.sort(listOfEmployees);
System.out.println("Sorted Alphabetically");
for (int i=0; i<listOfEmployees.size(); i++) {
System.out.println(listOfEmployees.get(i));
}
}
}
You need to implement Comparable
interface and override its compareTo
method like following:
public class Employee implements Comparable<Employee> {
String name;
public Employee(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
@Override
public int compareTo(Employee employee) {
return this.name.compareTo(employee.name);
}
}
And if you don't want to implement Comparable
interface then you have to create a custom Comparator
like follwing:
Comparator<Employee> employeeNameComarator = new Comparator<Employee>() {
@Override
public int compare(Employee employee1, Employee employee2) {
return employee1.name.compareTo(employee2.name);
}
};
And the pass the comparator object while sorting like:
Collections.sort(listOfEmployees, employeeNameComarator);
您还可以使用Comparator
。
listOfEmployees.sort(Comparator.comparing(Employee::getName));
You need to implement the Comparable interface in order to use Collections.sort(). Please go through below oracle docs for more information:
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.