在JAVA中尝试联合两个数组时获得额外的数字

Joh*_*igs 1 java

在我有一个任务我需要联合两个集合(整数数组),但由于某种原因,我得到错误的输出...

这是类集的属性:

private int []set; 
private int counter;
private int max = 10;
Run Code Online (Sandbox Code Playgroud)

这是我用来获取数字的构造函数(我需要使用varags,因为我需要能够更改集合中的元素数量):

public Set (int...numbers) {

        set = new int[max];
        counter = 0;

        for (int i = 0; i < numbers.length; i++) {

            if (!this.isMember(numbers[i])) { 
                this.set[this.counter] = numbers[i];
                this.counter++;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是union方法:

public Set union (Set setToUnion) {

    Set setToReturn;

    if (this.equals(setToUnion)){
        setToReturn = new Set(setToUnion);
        return setToReturn;
    }

    setToReturn = new Set(this.set);

    for (int i = 0; i < setToUnion.counter; i++) {

        if (!setToReturn.isMember(setToUnion.set[i])) {
            setToReturn.set[setToReturn.counter ] = setToUnion.set[i];
            setToReturn.counter++;
        }
    }
    return setToReturn;
}
Run Code Online (Sandbox Code Playgroud)

如果你想看看isMember在这里看起来如何,那就是(只是检查一些数字是否是其他集合的成员):

public boolean isMember (int n) {

        if (isEmpty()) {
            return false;
        }

        for (int i = 0; i < this.counter; i++) {

            if (n == this.set[i]) {
                return true;
            }
        }

        return false;
    }
Run Code Online (Sandbox Code Playgroud)

现在在程序中我创建了两个这样的集合:

Set someSet = new Set(1,2,3,4,5);       
Set anotherSet = new Set(2,6,7,8,9);

Set m = someSet.union(anotherSet);

m.show();
Run Code Online (Sandbox Code Playgroud)

但我得到的输出是(1,2,3,4,5,0,6,7,8,9),我需要相同的但中间没有0 ...

请帮助谢谢!

tob*_*bii 5

问题似乎是union方法中的这一行:

setToReturn = new Set(this.set);
Run Code Online (Sandbox Code Playgroud)

应该是:

setToReturn = new Set(this);
Run Code Online (Sandbox Code Playgroud)

为什么会导致问题?此时,this.setequals [1, 2, 3, 4, 5, 0, 0, 0, 0, 0],这是一个int数组.因此,将调用以下构造函数:

public Set (int...numbers) { ... }
Run Code Online (Sandbox Code Playgroud)

这意味着将添加数组中的所有数字,包括零.您需要通过执行以下操作来截断数组中的零:

setToReturn = new Set( Arrays.copyOf( set, counter ) );
Run Code Online (Sandbox Code Playgroud)

或者有一个接受一个的构造函数Set.这样你就可以访问counter,看看数组中有多少数字实际上是其中的一部分 Set.我猜你已经有了这个构造函数,基于调用这样一个构造函数的代码的另一部分.