2013-10-12 90 views
0

我不確定爲什麼我的removeDuplicates方法拒絕實際擺脫非唯一值。我不確定問題是否與尺寸增量或我的方法調用有關。刪除陣列中的冗餘值

// post: places the value in the correct place based on ascending order 
public void add(int value) { 
    size++; 
    if (size == 1) { 
     elementData[0] = value; 
     } else { 
      int position = Arrays.binarySearch(elementData, 0, size - 1, value); 
      if (position < 0) { 
      position = (-position) - 1; 
     } 
      for (int i = size - 1; i > position; i--) { 
      elementData[i] = elementData[i - 1]; 
     } 
      elementData[position] = value; 
     } 
    if (unique) { 
     removeDuplicates(); 
    } 
} 

//post: removes any duplicate values from the list 
private void removeDuplicates() { 
    for(int i = size - 1; i > 0; i--) { 
     if (elementData[i] == elementData[i - 1]){ 
      remove(i - 1); 
     } 
    } 
} 
+1

刪除(I - 1);這是一種方法嗎? –

+0

???「elementData」的類型是什麼?如果它是一個對象,則不能使用「==」。 – paulsm4

+0

elementData是一個整數的數組。 remove是一種接受索引的方法,刪除該索引處的值並滑動剩下的右側空間上的所有值。 – user98643

回答

0

試試這個..

//轉換它列爲我們需要的列表對象來創建 //設置對象。一個集合是一個集合對象,不能有 //重複的值,所以通過將數組轉換爲集合 //重複值將被刪除。

List<String> list = Arrays.asList(data); 
Set<String> set = new HashSet<String>(list); 

System.out.print("Remove duplicate result: "); 

// 
// Create an array to convert the Set back to array. 
// The Set.toArray() method copy the value in the set to the 
// defined array. 
// 
String[] result = new String[set.size()]; 
set.toArray(result); 
for (String s : result) { 
    System.out.print(s + ", "); 
1

@ user98643 -

Jano的的建議通過點上正確的:最好的解決方案是簡單地採用合適的數據結構,例如TreeSet

SUGGESTIONS:

1)在一般情況下,總是考慮使用偏好的容器這樣的「列表<>」到陣列

2)在一般情況下,尋找已具有大部分的容器你需要的屬性

3)在這種情況下,A)你想要所有的元素排序,並且B)每個元素必須是唯一的。

TreeSet很適合這項法案。

IMHO ..

http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html

http://math.hws.edu/javanotes/c10/s2.html

http://www.mkyong.com/java/what-is-the-different-between-set-and-list/