【问题标题】:Invalid argument to operation ++/-- in ArrayListArrayList 中操作 ++/-- 的参数无效
【发布时间】:2019-01-01 15:44:13
【问题描述】:

我想从点数组创建一个简单的二维直方图。

班级积分

import java.util.ArrayList;
import java.util.List;


public class Points {
    static List<List<Integer>> histogram = new ArrayList<List<Integer>>();

    public static void createHistogram(List<Point> point,int max) {     
        for(int x = 0; x < max; x++) {
            histogram.add(new ArrayList<Integer>());
            for(int y = 0; y < max; y++) {
                histogram.get(x).add(0);
                System.out.print((histogram.get(x).get(y)) +" ");
            }
            System.out.println();
        }

        for(int x = 0; x < point.size(); x++)
            histogram.get(point.get(x).x).get(point.get(x).y)++;
    }

    public static void main(String[] args) {
        List<Point> points = new ArrayList<Point>();

        points.add(new Point(0,10));
        points.add(new Point(1,2));
        points.add(new Point(2,5));
        points.add(new Point(1,2));


        createHistogram(points,10);
    }


}

点类

public class Point{
    public int x = 0;
    public int y = 0;

    Point(int x, int y){
        this.x = x;
        this.y = y;
    }
}

当我尝试增加直方图的值时,出现“操作参数无效 ++/--”错误。这是为什么?当我打印“histogram.get(point.get(x).x).get(point.get(x).y)”的值时,没有问题。为什么不允许更改其值?我该如何解决?

【问题讨论】:

  • histogram.get(point.get(x).x).get(point.get(x).y)++; 到底应该增加什么?

标签: java arrays list arraylist


【解决方案1】:

为什么会这样?

因为递增和递减运算符只能应用于变量(局部变量或类变量)或数组元素。您正在尝试将其应用于函数调用的返回值,但操作员无法知道如何将新值写回。

相反,您需要获取该值,将其加一,然后通过适当的 setter 方法设置该值。

需要明确的是,如果您尝试在 Point 实例上增加 xy,您可以使用 ++ 来做到这一点:

thePoint.y++;

histogram.get(point.get(x).x).get(point.get(x).y)++; 尝试在get 的返回值上执行此操作。

【讨论】:

    【解决方案2】:
    for(int x = 0; x < point.size(); x++)
            histogram.get(point.get(x).x).get(point.get(x).y)++;
    

    试试

    for(int x = 0; x < point.size(); x++) {
    
        List<Integer> list = new ArrayList<Integer>(histogram.get(point.get(x).x));
        list.set(point.get(x).y, point.get(x).y + 1);
        histogram.set(point.get(x).x, list);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-08
      • 2017-07-08
      • 1970-01-01
      • 2021-02-10
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多