2012-11-30 34 views
2

我有麻煩,使用SimpleSortingVector排序我的黑莓應用矢量。我的東西不排序它仍然是一樣的。如何使用SimpleSortingVector對黑莓中的矢量進行排序?

這裏是我迄今爲止...

MyComparator類

private Vector vector = new Vector(); //Assume that this vector is populated with elements already 
    SimpleSortingVector ssv = new SimpleSortingVector(); 
    ssv.setSortComparator(new Comparator() { 

     public int compare(Object o1, Object o2) { 

      Record o1C = (Record)o1; 
      Record o2C = (Record)o2; 
      return o1C.getName().compareTo(o2C.getName()); 
     } 

     public boolean equals(Object obj) { 
      return compare(this, obj) == 0; 
      } 
    }); 

for(int i=0;i<vector.size();i++){ 
        Record record = new Record(); 
     record=(Record) vector.elementAt(i); 
    //when you add elements to this vector, it is to post to be automatically sorted 
     ssv.addElement(record); 
    } 

類記錄

public class Record { 
    String name; 
    int price; 


    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 

    public int getPrice() { 
     return price; 
    } 
    public void setPrice(int price) { 
     this.price = price; 
    } 

}

回答

4

SimpleSortingVector不排序默認情況下。考慮到班級的名字,我第一次遇到這個問題,這對我來說是意料之外的。

你可以做兩件事之一。請致電SimpleSortingVector.setSort(true)以確保在每次更改後始終對矢量進行排序。令人驚訝的是,默認情況下這並未打開。 或者,您可以在將所有元素添加到矢量後調用SimpleSortingVector.reSort(),以在一個批處理操作中進行排序。

+0

+ 1,是的,你說得對,我的回答是絕望的嘗試。 – dreamcrash

+0

它的工作原理。謝謝。它比較快,負載較小SimpleSortingVector.setSort(true)或SimpleSortingVector.reSort()? – ejobity

+1

我看不到源代碼,所以我只能做出有根據的猜測。兩者應該有相同的漸近時間:O(n log n)。 reSort()應該能夠以稍小的常數因子進行排序,因此速度會更快一些。 –

相關問題