使用下面的代码。但是它以对象形式而不是字符串形式给出响应。让我知道我错了...

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Employee5 {

    String name;

    public String getName() {
        // TODO Auto-generated method stub
        return name.toString();
    }

    void setName(String nameOfEmp) {
        name = nameOfEmp;
    }

}

class EmpSortByName implements Comparator<Employee5> {
    public int compare(Employee5 o1, Employee5 o2) {
        return o1.getName().compareTo(o2.getName());
    }
}

public class ComparatorExampleInJava {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        Employee5 emp1 = new Employee5();
        emp1.setName("A");
        Employee5 emp2 = new Employee5();
        emp2.setName("C");
        Employee5 emp3 = new Employee5();
        emp3.setName("B");

        List lst = new ArrayList();
        lst.add(emp1);
        lst.add(emp2);
        lst.add(emp3);

        System.out.println("Before Sort : " + lst);

        try {
            Collections.sort(lst, new EmpSortByName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("After Sort  : " + lst);

    }
}


获取输出:
排序前:[Employee5 @ 19821f,Employee5 @ addbf1,Employee5 @ 42e816]
排序后:[Employee5 @ 19821f,Employee5 @ 42e816,Employee5 @ addbf1]

所需的输出:
排序前:[A,C,B]
排序后:[A,B,C]

最佳答案

您需要在Employee5中实现一个名为toString()的方法,该方法返回名称。

例如(添加到Employee5)

public String toString() {
    return name;
}


并进一步阅读:How to use the toString method in Java?

07-24 13:26