【问题标题】:Final variable being changed without any = statements在没有任何 = 语句的情况下更改最终变量
【发布时间】:2021-01-08 01:51:51
【问题描述】:

我正在java中制作一个供个人使用的自动点击项目,并使用以下方法从扩展MouseAdapter的类中获取点击坐标。点击是在 JFrame 上完成的。

            int[] mouseCoordinates = new int[2];   //The coordinates of the click
            mouseCoordinates = mouseListenerExample.getCoordinates();

            final int[] baseCoordinates = mouseCoordinates; //The base coordinates (no click) which is this problem//

            int[][] totalCoordinates = new int[4][2];  //An array that collects all coordinates of 4 mouse clicks


            for (int i = 0; i < 4; i++){ //the goal is to get the coordinates of 4 clicks

                while (mouseCoordinates[0] == baseCoordinates[0]){
                    mouseCoordinates = mouseListenerExample.getCoordinates(); //The problem occurs here: when mouseListenerExample.getCoordinates() changes, mouseCoordinates is changed, baseCoordinates is also changing, which it shouldnt, since there are no statements that say so.

                    if (mouseCoordinates[0] != baseCoordinates[0]) {
                        break;
                    }

                }

                totalCoordinates[i] = mouseListenerExample.getCoordinates();
                mouseListenerExample.setCoordinates(baseCoordinates);
                mouseCoordinates = baseCoordinates;
            }

是否有一些语句正在改变我缺少的 baseCoordinates?

【问题讨论】:

  • 我正在使用调试器来跟踪整个事情的进展,它正在改变两个数组的内容。如果这样可以更容易,我可以发布整个代码,我在这个网站上有点新。
  • 没关系,因为我看到了这个问题。请看答案。
  • 您可以使用 java.awt.Point 来保存一个 X、Y 坐标。

标签: java arrays swing integer


【解决方案1】:

您的baseCoordinates 变量已被声明为final,因此它无法更改,但由于它是int[] 或int-array,它是一个引用 变量,等等不能改变的是引用本身,而不是引用的状态,因此数组中保存的整数 can(在您的情况下 -- do)会改变。 p>

您正在更改mouseCoordinates 持有的值。由于baseCoordinates 指的是完全相同 int[] 对象,因此这同样会更改baseCoordinates 的值。如果你不想改变它,最好为 final 变量创建一个全新的 int 对象。

执行以下操作:

final int[] baseCoordinates = new int[mouseCoordinates.length];
System.arraycopy( mouseCoordinates, 0, baseCoordinates , 0, mouseCoordinates.length );

【讨论】:

  • 如果是你,你会加什么?我可以制作一个等于 0 的最终 int 并用它填充数组吗?
  • 我们有 2020 年。您可以使用 final int[] baseCoordinates = mouseCoordinates.clone();final int[] baseCoordinates = Arrays.copyOf(mouseCoordinates, mouseCoordinates.length); 手动使用 System.arraycopy 很少需要。
  • @BigBoi 也许,你最好不要使用数组。已经有一个Point 类。但是,如果您更喜欢不可变值类型,请创建自己的 Point,例如 final class Point { final int x, y; }。或者使用最新 JDK 的预览功能:record Point(int x, int y) {}
【解决方案2】:

所以在环顾四周之后,我只是用单独的整数替换了数组,并在中断之前添加了一个打印语句,它使它起作用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2013-09-25
    • 2019-03-29
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多