2014-12-06 80 views
1

我需要按照名稱排序列表,但我能夠做到這一點,請給它任何建議。
/* *要更改此模板,請選擇工具|模板 *並在編輯器中打開模板。 */ 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) 

回答

2

按照商務部對於只有列表作爲參數排序的方法,它說:

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

3

當使用Collections.sort(List<T> list),編譯器要求的類型T必須是可比較的(<T extends Comparable<? super T>>)。

這不是你的Person類的情況。要麼使Person類可比(通過實現Comparable接口),要麼使用過載的sort方法提供自定義比較器。

1

每當對象的名單上的調用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/