如何从数组列表中的指定位置获取值(处理)?

How can I get a value from a specified position in an array list (processing)?

我需要从数组列表中获取一个值。列表中的对象将一些值存储在变量(x 和 y 坐标)中。

我尝试使用 get() 函数,但它只 returns 一个像这样的字符串:linkTrackerTest$Object@20e76e47.

此外,我尝试过像 objects.get(0(x)) 这样的想法,但还没有奏效。

有人可以帮我解决这个问题吗?

提前致谢:-)

您得到的行为是完全正常的。

因为我猜你正在尝试打印 get 返回的对象,并且你没有为 ObjecttoString() 方法提供 Override ,最好的 Java 可以做的是打印所谓的 identity hashcode - "kinda of the memory address" of it.

尝试将以下内容添加为您的 class 的成员:

         @Override
        public String toString() {
            return x+" "+y;
        }

这样你尝试打印你的class,Java会自动调用提供的toString()

  • 这里的问题不在于您访问 ArrayList 的元素的方式,您需要使用 get 方法。

你得到那个奇怪的字符串是因为它返回数据的内存地址而不是数据本身,因为 java 隐式调用 toString()

尝试:

yourObject x = list.get(i);

int x = list.get(i).xValue; / int y = list.get(i).yValue;

或者通过编写您自己的

完全覆盖toString()

不确定这是否是您要问的,但如果您有对象列表 您可以使用对象 class

中的 getter 方法获取您正在寻找的值
public class Obj {

     private int x;
     private int y;

     // constructor in which x, y values are given 
     public Obj(int x_val, int y_val) {
          this.x = x_val;
          this.y = y_val;
     }

     // getter
     public int get_x() {
          return this.x;
     }

     public int get_y() {
          return this.y;
     }



 public static void main(String[] args) {

      List<Obj> Obj_Lst = new ArrayList<Obj>();

      // adding objects to list
      Obj_Lst.add(new Obj(1,6));
      Obj_Lst.add(new Obj(2,5));
      Obj_Lst.add(new Obj(3,4));

      // getting values from object
      System.out.println(Obj_Lst.get(0).get_x());

 }

}

输出

1