2012-04-28 41 views
-2

我有一個數組列表,現在我想對它進行排序,我的ArrayList中包含重複的元素太多,重複的元素也應在最終的結局除去排序列表,請指教關於列表的排序不反覆

ArrayList list=new ArrayList(); 
     list.add("Ram"); 
     list.add("Dinesh"); 
     list.add("Sachin"); 
     list.add("Dinesh"); 
+0

Collections.sort() – 2012-04-28 04:48:56

+0

@Balaswamyvaddeman,我已經編輯我的問題,謝謝 – dghtr 2012-04-28 04:50:39

+1

這聽起來像一個家庭作業的問題,如果是,請編輯的問題有「功課」的標籤。 – David 2012-04-28 04:52:17

回答

1

排序是不可能的,沒有一些迭代,但你不必自己做。 嘗試使用有序集合的排序上插入並刪除重複:

list = new ArrayList<String>(new TreeSet<String>(list)); 

基本上你把列表內容到一個有序集合(在這種情況下TreeSet),然後設置的內容重新複製到一個新的列表。

+0

嗨托馬斯,非常感謝你能提供一個詳細的例子......這將使理解更加清晰。 – dghtr 2012-04-28 05:52:17

+0

@ user1336909我的示例應該建立在你的頂部幷包含你要求的所有內容。你還需要什麼? – Thomas 2012-04-28 19:04:59

0

同上。如果您正在對您創建的對象的集合進行排序,則需要讓Collections和Arrays知道如何比較對象。

import java.util.Arrays; 

public class delme { 
    public static void main(String[] args) 
    { 

     SomeData[] theData = new SomeData[5]; 
     theData[0] = new SomeData("zzzz", 1); 
     theData[1] = new SomeData("aaaa", 1); 
     theData[2] = new SomeData("zzzz", 0); 
     theData[3] = new SomeData("aaaa", 0); 
     theData[4] = new SomeData("aaaa", 0); 

     Arrays.sort(theData); 

     for (int i = 0; i < theData.length; i++){ 
      System.out.println("theData[" + i + "]=" + theData[i].toString()); 
     } 
    } 
    } 


    public class SomeData implements Comparable { 

    public String someData1; 
    public int someData2; 


    public SomeData(String s, int i) { 
     someData1 = s; 
     someData2 = i; 
    } 


    //return -1 if this object should come before the arguments object in a sorted list 
    //return 0 if they have the same value 
    //return 1 if this object should come after in a sorted list 
    public int compareTo(Object arg0) throws ClassCastException { 
     if (!(arg0 instanceof SomeData)) //we must accept type Object so lets check to make sure its of type SomeData 
      throw new ClassCastException("peram given is not a SomeData object"); 

     SomeData otherData = (SomeData)arg0; //lets cast it to our data type for ez access 
     if (someData2 == otherData.someData2) 
      return someData1.compareTo(otherData.someData1); 
     return Integer.compare(someData2, otherData.someData2); 
    } 

    public String toString() { 
     return "someData1=" + someData1 + ", someData2=" + someData2; 
    } 
    }