2

我删除重复数字的方法有效,但如果数字出现两次以上则无效。例如,编号为 1,2,2,3,4,5,6,7,7,7,8,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);
            }

    }

}

  }
4

2 回答 2

3

维基百科指出一个实用程序类:

是一个类,它定义了一组方法,这些方法执行常见的、经常重复使用的功能。大多数实用程序类在静态(请参阅静态变量)范围内定义这些常用方法。

最好给你的实用程序类一个私有构造函数(这样它就永远不能被初始化),即

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

(顺便提一下,Joshua Bloch 在 Effective Java 中对此进行了讨论)

于 2014-01-21T05:38:46.370 回答
0

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

public final class SortAndRemove{
 private SortAndRemove() {
  throw new AssertionError();
 }
 ... // Remainder omitted
}
于 2014-01-21T08:02:30.863 回答