2013-10-12 91 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/