从数组中删除元素和重复的方法

时间:2017-06-19 22:18:15

标签: java arrays for-loop

考虑下面给出的代码:

public class Lista {

private int[] numbers;
private int capacity;
private int size;

public Lista (int capacity) {
    this.size = 0;
    this.capacity = capacity;
    this.numbers = new int[capacity];
}

public void addElement(int element) {
    if (size == capacity) {
        System.out.println("Array numbers is full");
        return;
    }
    numbers[size++] = element;
        }

 public void removeFirst(int x) {
    for (int i = 0; i < size; i++) {
        if (numbers[i] == x) {
            for (int y = i; y < size; y++) {
                numbers[y] = numbers[y + 1];
            } break;
        } size--;
    }
}

public void removeDuplicates() {
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (numbers[i] == numbers[j]) {
                for (int y = j; y < size; y++) {
                    numbers[y] = numbers[y + 1];
                } size--;
            }
        }
    }
}

public static void main(String[] args) {
    Lista lista = new Lista(10);
    lista.addElement(1);
    lista.addElement(2);
    lista.addElement(3);
    lista.addElement(2);
    lista.addElement(5);
    lista.addElement(2);
    lista.addElement(7);

关于方法removeFirst和removeDuplicates是否有比我使用的结构更好的方法(更快,更清晰)? removeFirst方法应该删除作为参数给出的int的第一个发生。 removeDuplicates方法应该从数组中删除任何重复项。 我将不胜感激任何建议

2 个答案:

答案 0 :(得分:0)

总结评论:

    public void removeFirst(int x) {
        for (int i = 0; i < size; i++) {
            if (numbers[i] == x) {
//                for (int y = i; y < size; y++) {
//                    numbers[y] = numbers[y + 1];
//                }
                System.arraycopy(numbers, i + 1, numbers, i, size - i);
                size--;
                return;
            }
        }
    }

    public void removeDuplicates() {
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                if (numbers[i] == numbers[j]) {
//                    for (int y = j; y < size; y++) {
//                        numbers[y] = numbers[y + 1];
//                    }
                    System.arraycopy(numbers, i + 1, numbers, i, size - i);
                    size--;
                }
            }
        }
    }

答案 1 :(得分:0)

在if语句中添加了j--,因为当数组中有一个接一个的相同数字时,它无法正常工作。现在它工作正常。谢谢!

public void removeDuplicates() {
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (numbers[i] == numbers[j]) {
             }
                System.arraycopy(numbers, i + 1, numbers, i, size - i);
                size--;
                j--;
            }
        }
    }
}