Java 如何在此处引用数组

Java 如何在此处引用数组,java,arrays,Java,Arrays,这是我的代码片段: public NaturalNumberTuple toSet() { int newTuple[] = new int[tuple.length]; boolean checkIfYouHadToRemoveSomething = false; for(int i : newTuple){ newTuple[i] = tuple[i]; } for(int i : newTuple){ for(int

这是我的代码片段:

public NaturalNumberTuple toSet() 
{
    int newTuple[] = new int[tuple.length];
    boolean checkIfYouHadToRemoveSomething = false;
    for(int i : newTuple){
        newTuple[i] = tuple[i];
    }
    for(int i : newTuple){
        for(int j : tuple){
            if(newTuple[i] == tuple[j]){
                NaturalNumberTuple placeholderTuple = remove(tuple[j]);
                newTuple[i] = tuple[j];
                checkIfYouHadToRemoveSomething = true;
            }
        }
    }
    if(checkIfYouHadToRemoveSomething){
        return placeholderTuple;//Problem
    } else {
        return new NaturalNumberTuple(tuple);
    }
}
该方法返回一个新的
NaturalNumberTuple
,但不包含给定的数字(此处为
tuple[j]
)。 我的
toSet()
方法应该给我与我给它的数组相同的数组,但每个数字只出现一次。 我的问题在标有(//问题)的行中。 问题在于
占位符元组
未定义为变量。我知道不是,但如果我在方法的开头写:

NaturalNumberTuple placeholderTuple;
在我最初定义占位符元组的那一行:

placeholderTuple = remove(..);
它给了我一个错误,
占位符元组
可能尚未初始化

我知道为什么会出现这些错误,但我真的不知道如何修复。
如果有人试图使用
ArrayList
s优化我的代码,请不要这样做,因为我不允许使用它们(不确定它们在这里是否有用,但在其他代码段它们会有用)。

在方法的开头,写下:

NaturalNumberTuple placeholderTuple = null;
这将使该变量在方法结束前保持可见,并将其初始化为默认值

然后,在循环中进行更改:

NaturalNumberTuple placeholderTuple = remove(tuple[j]);


在代码开头声明并初始化它,如下所示:

NaturalNumberTuple placeholderTuple = null;
在循环中,只需初始化它,而不需要重新定义,比如
placeholderTuple=remove(tuple[j])并且它应该可以工作

我认为您的代码将始终返回newTuple的最后一个条目,它类似于tuple,因此对我来说没有意义。如果只想删除第一个匹配项,可以不使用两个循环,如:

placeholderTuple = remove(tuple[0]);
placeholderTuple = remove(tuple[0]);