我很好奇数组索引在这里是如何工作的,因为它可以工作,但我很困惑为什么

问题描述 投票:0回答:1
public Polynomial add(Polynomial other){
  int max = Math.max(coefficients.length, other.coefficients.length);
  int[] newPoly = new int[max];
  for (int i=0; i<max; i++){
    if (i<coefficients.length){
      newPoly[i] += coefficients[i];
    }   
    if (i<other.coefficients.length){
      newPoly[i] += other.coefficients[i];
    }   
  }
  return new Polynomial(newPoly);
}

为什么这有效?索引

i
处的数组现在是否应该设置并且不可变,因为它是一个数组。那么,如果两个
if
语句都允许的话,为什么还要添加到索引呢。

java arrays indexing addition
1个回答
0
投票

这是我对代码的解释:

import java.util.*;
public class Stack{
    public Polynomial add(Polynomial other){
        // this finds the biiger polynomial of the two
        int max = Math.max(coefficients.length, other.coefficients.length);
        
        // this array is not going out of bounds of the bigger polynomial
        int[] newPoly = new int[max];
        
        // Go till the max
        for (int i=0; i<max; i++){
            // i should not go over the length of the smaller polynomial thefore there are 2 if statements
            if (i<coefficients.length){
                newPoly[i] += coefficients[i];
            }   
            if (i<other.coefficients.length){
                newPoly[i] += other.coefficients[i];
            }   
        }
        
        // then it makes a polynomial using the new arr
        return new Polynomial(newPoly);
    }
}

但基本上 i 从 0 开始直到 0 结束。我不确定你通过“ i 现在被设置并且不可变,因为它是一个数组”推断出什么。但是,是的,你是正确的,数组是不可变的,并且此方法绝不试图更改数组的大小。

© www.soinside.com 2019 - 2024. All rights reserved.