Java 向量堆栈包含实现

Java Vector Stack Contains Implementation

我的包含和删除方法没有返回正确的输出。该程序获取一堆名称并使用 contains、remove 和 empty 方法。我写了我的方法,我正在使用一个驱动程序来查看我是否正确地写了我的方法。我很确定我的所有方法都是正确的,除了 contains 和 remove 方法。这是我的代码


    public boolean remove(T obj) {
        if (obj == null)
            return false;
        while (!store.empty() && store.peek().compareTo(obj) < 0) {
            temp.push(store.pop());
        }

        store.pop();

        while(!temp.empty()) {
            store.push(temp.pop());
        }
        size--;
        return true;
    }

public boolean contains(T obj) {
    while (!store.empty() && store.peek().compareTo(obj) < 0) {
        if (store.peek().equals(obj)) {
            return true;
        } else temp.push(store.pop());
    }
    while(!temp.empty()) {
        store.push(temp.pop());
    }
    return false;
}

以下是方法 remove 和 contains 的实现:

public boolean remove(T obj) {
    if (obj == null)
        return false;
    boolean removed = false;
    while (!store.empty()) {
        if(store.peek().equals(obj)) {
            store.pop();
            size--;
            removed = true;
        }else {
            temp.push(store.pop());
        }
    }

    while (!temp.empty()) {
        store.push(temp.pop());
    }
    return removed;
}

public boolean contains(T obj) {
    while (!store.empty()) {
        if (store.peek().equals(obj)) {
            return true;
        } else
            temp.push(store.pop());
    }
    while (!temp.empty()) {
        store.push(temp.pop());
    }
    return false;
}

您实施 remove 的问题是没有 if 语句来测试对象的相等性,应该将其删除。 remove 方法也返回 true 并递减大小,无论对象是否被删除。

contains 方法的问题是它从不测试对象的相等性。


您应该应用 DRY(不要重复自己)原则。考虑到这一点,您应该提取代码

    while (!temp.empty()) {
        store.push(temp.pop());
    }

进入单独的方法,不要一次又一次地重复相同的代码。像这样:

private void pushFromTempToStore(){
    while (!temp.empty()) {
        store.push(temp.pop());
    }
}

您的方法可能如下所示:

public boolean add(T obj) {
    if (obj == null)
        return false;
    while (!store.empty() && store.peek().compareTo(obj) < 0) {
        temp.push(store.pop());
    }
    store.push(obj);
    pushFromTempToStore();
    size++;
    return true;
}

public boolean remove(T obj) {
    if (obj == null)
        return false;
    boolean removed = false;
    while (!store.empty()) {
        if(store.peek().equals(obj)) {
            store.pop();
            size--;
            removed = true;
        }else {
            temp.push(store.pop());
        }
    }

    pushFromTempToStore();
    return removed;
}


public boolean contains(T obj) {
    while (!store.empty()) {
        if (store.peek().equals(obj)) {
            return true;
        } else
            temp.push(store.pop());
    }
    pushFromTempToStore();
    return false;
}

另一个需要记住的重要事情是测试。您应该使用一些测试框架,如 JUnit 或 TestNG,而不是驱动程序。有很多材料可以学习有关测试的知识。这是一本对我帮助很大的好书 Test-Driven Java Development。它有点过时,所以也许你应该尝试找到一些更新的资源...