我希望我也可以提出问题,而不是真正有错误并需要解决它们。

我得到以下代码:

public boolean equals(NaturalNumberTuple givenTuple) {
    int count = 0;
    if(tuple.length == givenTuple.getLength()){
        for(int i = 0; i < tuple.length; i++){
            if(this.tuple[i] == givenTuple.tuple[i]){
                count++;
            }
        }
        if(count == tuple.length){
            return true;
        }
    }
    return false;
}


如您所见,我正在使用普通的for循环,但是我了解到可以使用所谓的foreach循环

for(int i : tuple){...}


但是,如果我尝试使用它,并且尝试检查两个Arrays是否相等,则会收到错误消息“ ArrayIndexOutOfBoundsException”。

有人可以解释一下为什么我不能在这里使用foreach循环吗?

最佳答案

我唯一的选择是您写了:

for(int i : tuple){
    if(this.tuple[i] == givenTuple.tuple[i]){
        count++;
    }
}


在for-each循环中,i获取数组中元素的值。不是索引。假设您有:

int[] arr = {1, 4, -2};


i将取值1、4和-2,而不是0、1、2。

当您需要索引来访问givenTuple.tuple[i]时,我认为您可以坚持使用传统的for循环,或使用Arrays.equals(那将是一种形式)。

还要注意,public boolean equals(NaturalNumberTuple givenTuple)不能替代equals方法(这可能会给您带来意外的惊喜)

09-30 13:37
查看更多