![](/img/trans.png)
[英]How to access (modify, add elements) to an ArrayList/Collection in an Inner class in java?
[英](Java) How to access, add, get class object in ArrayList?
这是我的小代码。 当我最后尝试 sysout list.get(i) 时。 它总是显示错误的数据,即使 get(0) 也不是最初添加的 0,0 数据。 但是当我 sysout 时,y_pos 和 x_pos 是正确的。 那么谁能帮助或指导我如何正确使用它呢? * 错误数据意味着:i~list.length 的所有数据都相同 *
import java.util.*;
class POS{
int x_pos, y_pos;
public void setpos(int x, int y){
this.x_pos = x;
this.y_pos = y;
}
}
class Solution {
public int solution(String dirs) {
int answer = 0;
ArrayList<POS> list = new ArrayList<POS>();
POS pos = new POS();
int x_pos = 0, y_pos = 0;
pos.setpos(0,0);
list.add(pos);
for(int i=0; i<dirs.length(); ++i)
{
switch(dirs.charAt(i)){
case 'L' : x_pos = x_pos - 1; break;
case 'R' : x_pos = x_pos + 1; break;
case 'U' : y_pos = y_pos + 1; break;
case 'D' : y_pos = y_pos - 1; break;
}
if(x_pos < -5 || x_pos > 5 || y_pos < -5 || y_pos > 5) continue;
else{
pos.setpos(x_pos,y_pos);
list.add(pos);
}
}
for(int i=0; i<list.size(); ++i){
System.out.println(list.get(i).x_pos + " " + list.get(i).y_pos);
}
return answer;
}
}
在添加到列表之前,您需要创建新的 POS 的 object(假设您想要 POS 对象列表)
需要在第二个集合pos的属性中新建pos(也就是在for循环中),否则设置时pos的数据会发生变化,但是列表中元素的指针全部指向原来的pos object,导致最终使用sysout时,列表中的所有数据都是您最后设置的数据。 据我目前的能力所知,当您想使用通用列表添加元素时,您只能这样做。 如果有更好的操作方法,希望告知。
需要在第二个集合pos的属性中新建pos(也就是在for循环中),否则设置时pos的数据会发生变化,但是列表中元素的指针全部指向原来的pos object,导致最终使用sysout时,列表中的所有数据都是你最后设置的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.