需要按排序顺序排序在java中的名称

问题描述:

我需要按照名称排序列表,但我能够做到这一点,请给它任何建议。
/* *要更改此模板,请选择工具|模板 *并在编辑器中打开模板。 */ package javaexception;需要按排序顺序排序在java中的名称

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

/** 
* 
* @author Admin 
*/ 
class person 
{ 
    int id; 
    String name; 
}; 

public class JavaException 
{ 
    public static void main(String a[]) 
    {   
     List<person> li =new ArrayList<person>(); 
     person p=new person(); 
     p.id=1; 
     p.name="Sushant"; 
     li.add(p); 
     person p1=new person(); 
     p1.id=2; 
     p1.name="Atul"; 
     li.add(p1); 
     person p2=new person(); 
     p2.id=3; 
     p2.name="Genu"; 
     li.add(p2); 
     System.out.println(""+li); 
     Collections.sort(li); 
     for(int i=0;i<li.size();i++) 
     { 
      person pp=(person)li.get(i); 
      System.out.println(""+pp.name); 
     } 
    } 
} 

它gaves我一个错误

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.util.Collections.sort 
[[email protected], [email protected], [email protected]] 
    at javaexception.JavaException.main(JavaException.java:41) 

按照商务部对于只有列表作为参数排序的方法,它说:

Sorts the specified list into ascending order, according to the 
Comparable natural ordering of its elements. 
All elements in the list must implement the Comparable 
interface. Furthermore, all elements in the list must be 
mutually comparable (that is, e1.compareTo(e2) 
must not throw a ClassCastException for any elements 
e1 and e2 in the list). 

所以,你的个人类本身不具有可比性,因此你会以两种方式解决此问题:

  • 为您的人员类实现Comparable接口并实现compareTo方法。喜欢的东西:

    class person implements Comparable<person> 
    { 
    int id; 
    String name; 
    @Override 
    public int compareTo(person o) { 
        return this.name.compareTo(o.name); 
    } 
    }; 
    
  • 使用另一种类型的API,这需要比较作为参数是这样的:

    Collections.sort(li, new Comparator<person>() { 
    @Override 
    public int compare(person o1, person o2) { 
    return o1.name.compareTo(o2.name); 
    }}); 
    
+0

@ZouZou感谢我没有意思o1.name/o2.name。已更新相同。 – SMA 2014-12-06 13:39:52

当使用Collections.sort(List<T> list),编译器要求的类型T必须是可比较的(<T extends Comparable<? super T>>)。

这不是你的Person类的情况。要么使Person类可比(通过实现Comparable接口),要么使用过载的sort方法提供自定义比较器。

每当对象的名单上的调用Collections.sort()。然后java不知道要对其进行排序的字段。在你的情况下,你有id和名字。 java将如何推断您是否要对名称或标识进行排序。 所以,你需要提及排序的标准。

要做到这一点,你可以做如下: -

让你的个人类扩展可比

class person implements Comparable 

,然后实现compareTo方法。所以,当你调用Collections.sort()时,java将调用person.compareTo来比较和排序对象。

另一种方法是使用比较

http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/