Java 在没有任何=语句的情况下更改最终变量

Java 在没有任何=语句的情况下更改最终变量,java,arrays,swing,integer,Java,Arrays,Swing,Integer,我正在用java制作一个供个人使用的自动单击项目,并使用以下方法从扩展MouseAdapter的类中获取单击的坐标。正在JFrame上执行单击 int[] mouseCoordinates = new int[2]; //The coordinates of the click mouseCoordinates = mouseListenerExample.getCoordinates(); final int[] b

我正在用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;
            }
int[]鼠标坐标=新的int[2]//单击的坐标
mouseCoordinates=mouseListenerExample.getCoordinates();
最终int[]基准坐标=鼠标坐标//基本坐标(无点击)是这个问题的根源//
int[][]总坐标=新的int[4][2]//收集4次鼠标单击的所有坐标的数组
对于(inti=0;i<4;i++){//目标是获得4次单击的坐标
while(鼠标坐标[0]==基本坐标[0]){
mouseCoordinates=mouseListenerExample.getCoordinates();//问题出现在这里:当mouseListenerExample.getCoordinates()更改时,mouseCoordinates会更改,baseCoordinates也会更改,但它不应该更改,因为没有这样的语句。
if(鼠标坐标[0]!=基本坐标[0]){
打破
}
}
totalCoordinates[i]=mouseListenerExample.getCoordinates();
mouseListenerExample.setCoordinates(基本坐标);
鼠标坐标=基准坐标;
}

是否有一些语句正在更改我缺少的基本坐标?

您的
baseCoordinates
变量已声明为
final
,因此它无法更改,但由于它是
int[]
或int数组,它是一个引用变量,因此无法更改的是引用本身,而不是引用的状态,因此数组中的int可以(在您的例子中是--do)更改

您正在更改鼠标坐标所持有的值。由于
基本坐标
引用的是完全相同的
int[]
对象,因此这同样会更改
基本坐标
的值。如果不想更改,最好为最终变量创建一个全新的int对象

做一些类似于:

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

因此,在仔细查看之后,我只是用单个int替换了数组,并在中断之前添加了一个print语句,这使它能够正常工作。

我正在使用调试器跟踪整个过程,它正在更改两个数组的内容。我可以发布整个代码,如果这会使它更容易,我在这个网站上有点新。没关系,因为我看到了问题。请看答案。您可以使用java.awt.Point来保持一个X,Y坐标。如果是您,您会添加什么?我能做一个等于0的最终整数并用它填充数组吗?我们有2020。您可以使用
final int[]baseCoordinates=mouseCoordinates.clone()
最终int[]baseCoordinates=数组.copyOf(鼠标坐标,鼠标坐标.length)
使用
系统。很少需要手动使用arraycopy
。@BigBoi也许,你最好不要使用数组。已经有一个
类。但是如果您更喜欢不可变的值类型,请创建自己的
,比如
最终类点{final int x,y;}
。或者使用最新JDK的预览功能:
记录点(intx,inty){}