2013-08-07 54 views
0

使用下面的一段代码。但它是以对象形式给出响应而不是String。让我知道我错了......比较器 - 没有得到预期的结果

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]

回答

0

看来,你应该有自己的toString()implementtaion以指定如何:

例如(添加到Employee5)

public String toString() { 
    return name; 
} 

,并为进一步阅读打印出来:你的列表

class Employee5 { 
    ... 

    @Override 
    public String toString() { 
     return name; 
    } 

} 
0

当您在打印列表,toString()方法被调用它通过调用toString打印内容()会见被包含的对象的点数。您需要在您的Employee5类中重写toString()方法并从中返回名称。

0
Iterator itr = lst.iterator(); 
    while(itr.hasNext()) { 
    Employee5 element = (Employee5) itr.next(); 
    System.out.print(element.getName()); 
    } 

希望这会有所帮助。

相关问题