比较两个可调整大小的数组

时间:2017-02-10 23:17:28

标签: java

我试图找到我使用修改后的Set接口创建的两个ResizableArraySet对象的并集和交集,该接口有一些方法被删除。我很难通过这两套并处理它们。我知道这不是究竟发生了什么,但这里有一些代码可以更好地解释我想要做什么。这是我的测试人员的电话。

System.out.println(Arrays.toString((set.union(set2)).toArray()));

所以set是我在测试器中创建的对象,而set2是另一个我要与set进行比较的ResizableArraySet对象。当我打印它时,我只得到一个set2数组。

以下是构造函数和实例变量。

public class ResizableArraySet<T> implements Set<T> {

private int numberOfEntries;
private int size;
T[] array;

/**
 * Constructor for Set without size variable (Default size is 10)
 */
@SuppressWarnings({ "unchecked" })
public ResizableArraySet() {
    array = (T[]) new Object[10];
}

/**
 * Constructor for the Set with size variable
 * 
 * @param size
 */
@SuppressWarnings({ "unchecked" })
public ResizableArraySet(int size) {
    this.size = size;
    array = (T[]) new Object[size];
}

这是我的union方法的相关代码。如果交集方法是必要的,我可以在编辑中提供,但我认为两种方法中的问题是相同的。

@SuppressWarnings({ "unchecked", "unused" })
@Override
public Set<T> union(Set<T> anotherSet) {
    T[] newArray = (T[]) new Object[anotherSet.getSize()];
    int entries = this.size;
    System.out.println(entries); //Get 0, when the size is not 0
    for (int x = 0; x < entries; x++) {
        if (anotherSet.contains(array[x]) == false) {
            anotherSet.add(array[x]);
        }
    }
    return anotherSet;
}

这是我的添加,删除和包含方法

    @Override
public boolean add(T newEntry) {
    if (contains(newEntry)) {
        return false;
    } else if (array.length > numberOfEntries) {
        array[numberOfEntries] = newEntry;
        numberOfEntries++;
        return true;
    } else {
        array = Arrays.copyOf(array, (array.length * 2));
        array[numberOfEntries] = newEntry;
        numberOfEntries++;
        return true;
    }
}

@Override
public boolean remove(T anEntry) {
    if (contains(anEntry) != true) {
        return false;
    }
    for (int x = 0; x < numberOfEntries; x++) {
        if (array[x].equals(anEntry)) {
            // Loop to move the values down one index in the main array
            for (int a = x; a < numberOfEntries; a++) {
                array[a] = array[a + 1];
            }
            numberOfEntries--;
        }
    }
    return true;
}

@Override
public boolean contains(T anEntry) {
    for (int x = 0; x < numberOfEntries; x++) {
        if (array[x].equals(anEntry)) {
            return true;
        }
    }
    return false;
}

总结我的问题。我无法比较两个对象,因为它们都必须使用相同的方法[contains(anEntry),add(anEntry),getSize()]

如果我遗漏任何有用的代码,请告诉我。 有没有人能解决我的问题

1 个答案:

答案 0 :(得分:1)

以下是你的工会应该是什么样子。它使用了一个你需要实现的迭代器。这是因为您的otherSet变量的类型为Set<T>,而不是ResizableArraySet<T>,因此您无法直接访问其数组。

public Set<T> union(Set<T> anotherSet) {
    ResizableArraySet<T> newSet = new ResizableArraySet<>();
    for (int i = 0; i < numberOfEntries; i++) {
        newSet.add(array[i]);
    }
    Iterator<T> it = anotherSet.iterator();
    while (it.hasNext()) {
        T el = it.next();
        if (!newSet.contains(el)) {
            newSet.add(el);
        }
    }
    return newSet;
}
相关问题