为什么我的removeDuplicates方法只在第一次遇到它时才删除重复的整数?

时间:2014-01-21 05:26:36

标签: java list random selection-sort utility-method

我删除重复数字的方法有效,但如果数字出现的次数超过两次则无效。 例如使用该方法时,编号为1,2,2,3,4,5,6,7,7,7,9,9的清单给出了清单1,2,3,4,5,6,7,7, 8,9

import java.util.*;
public class final SortAndRemove{
  private SortAndRemove(){
    }
public static void selectionSort(List<Integer> a){
    if(a == null)
        return;
    if (a.size() == 0 || a.size() == 1)
        return;

    int smallest;
    int smallestIndex;
    for (int curIndex = 0; curIndex < a.size(); curIndex++) {

        smallest = a.get(curIndex);
        smallestIndex = curIndex;

        for (int i = curIndex + 1; i < a.size(); i++) {
            if (smallest > a.get(i)) {

                smallest = a.get(i);
                smallestIndex = i;
            }
        }


        if (smallestIndex == curIndex);

        else {
            int temp = a.get(curIndex);
            a.set(curIndex, a.get(smallestIndex));
            a.set(smallestIndex, temp);
        }

    }
}


public static void removeDuplicates(List<Integer> a){
    if(a == null)
        return;
    if (a.size() == 0 || a.size() == 1)
        return;
    for(int curIndex = 0; curIndex <a.size(); curIndex++){
        int num = a.get(curIndex);
            for(int i = curIndex + 1; i < a.size(); i++){
                if(num == a.get(i))
                    a.remove(i);
            }

    }

}

  }

2 个答案:

答案 0 :(得分:3)

Wikipedia states表示实用程序类:

  

是一个定义一组常用的方法的类   重复使用的功能。大多数实用程序类定义这些常用方法   在static下(参见静态变量)范围。

最好为您的实用程序类提供一个私有构造函数(以便永远不会初始化) 即。

public class SortAndRemove{
 private SortAndRemove() {
  throw new AssertionError();
 }
 ... // Remainder omitted
}

(顺便提一下,这是由Joshua Bloch在Effective Java中讨论的)

答案 1 :(得分:0)

最好使你的实用程序类最终(所以没有类可以从你的实用程序扩展,因为所有方法都是静态的)

public final class SortAndRemove{
 private SortAndRemove() {
  throw new AssertionError();
 }
 ... // Remainder omitted
}