无法在数组类型 ArrayList<Integer>[] 上调用 get(int),即使 get 方法适用于 ArrayLists

Cannot invoke get(int) on the array type ArrayList<Integer>[], even though the get method is applicable to ArrayLists

我正在编写一个方法,该方法采用 ArrayList 并在不同位置使用特定索引处的元素,但是当我在代码中使用 .get(int) 方法时,出现错误。

static void linreg(ArrayList<Integer> x[], ArrayList<Integer> y[]) {

        double sum_x = 0, sum_y = 0, int n = 15;
        
        for (int i = 0; i < n; i++) {

          sum_x += x.get(i); - Cannot invoke get(int) on the array type ArrayList<Integer>[]
          sum_y += y.get(i); - Cannot invoke get(int) on the array type ArrayList<Integer>[] 

有办法解决这个问题吗?谢谢

x 不是 ArrayList<Integer> 类型,而是 ArrayList<Integer>[] 类型。 (请注意,由于您的困惑,不建议使用此语法。)也许您并不是要同时拥有数组和列表。

参数xy是数组。 java 中的数组没有 get 方法。这就是你得到错误的原因。您甚至不需要将它们作为数组。您只需要将它们作为具有 get 方法的列表。

static void linreg(List<Integer> x, List<Integer> y) {

        double sum_x = 0, sum_y = 0, int n = 15;
        
        for (int i = 0; i < n; i++) {

          sum_x += x.get(i); 
          sum_y += y.get(i);
        }
        System.out.println(sum_x);
        System.out.println(sum_y);
 }