【问题标题】:Accessing elments from ArrayList从 ArrayList 访问元素
【发布时间】:2014-03-10 11:45:22
【问题描述】:

我已经学会了如何Create an Arraylist of Objects,这样的数组本质上是动态的。例如要创建具有 3 个字段的对象数组(类矩阵的实例),代码如下所示:

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

此外,Matrices 类是这样的:

public class Matrices{
int x;
int y;
int z;

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

现在,我如何访问此数组名称 list 中任何元素的每个字段?具体来说,如何从该数组的第二个元素(其值为(1,2,20))访问20字段?

【问题讨论】:

  • 请检查 Java API 以了解这些基本问题。

标签: java arrays arraylist


【解决方案1】:

您只需使用get 方法:

// 2nd element; Java uses 0-based indexing almost everywhere
Matrices element = list.get(1);

之后您对Matrices 引用的处理取决于您 - 您已经展示了构造函数调用,但我们不知道这些值随后是否作为属性或其他任何内容公开。

一般来说,当您使用一个类时,您应该查看它的文档 - 在本例中为 documentation for ArrayList。查看方法列表,尝试找到与您正在尝试执行的操作相匹配的方法。

您还应该阅读tutorial on collections 以了解有关 Java 集合库的更多信息。

【讨论】:

  • 正是这个文档是我所需要的。我会收藏它以备将来参考。谢谢
  • 你能帮我用 for-each 构造遍历 ArrayList 的每个元素吗?
  • @KunalKrishna:不,有很多的例子。我希望几乎所有关于增强 for 循环的教程都可以使用它作为示例。 Stack Overflow 非常适合解决非常具体的问题,但它不是从头开始学习语言的好方法。你最好有一本好书来完成。
【解决方案2】:

Matrices element = list.get(1); 将完成这项工作。 ArrayList 是一个零索引集合。所以list.get(1) 将给出第二个元素。

你应该检查相关的api,这里ArrayList

【讨论】:

    【解决方案3】:

    我认为这是一个搜索算法问题。

    您遍历list,并检查当前迭代的元素是否包含所需的值。

    【讨论】:

    • 我认为这不是 OP 想要的 - 他专门尝试访问第二个元素,所以只需调用 list.get(1) 即可。
    • @JonSkeet In particular, how to access the 20 field from 2nd element of this array whose value is (1,2,20) 这对我来说感觉相当模糊。
    • 是的,但是您的回答也没有解决“如何访问 20 字段”...
    【解决方案4】:
    Matrices m = list.get(1)
    

    请阅读 java 文档

    【讨论】:

      【解决方案5】:
      Matrice m = list.get(1);
      int twenty = m.getThirdElement(); // or whatever method you named to get the 3rd element (ie 20);
      
      // in one go :
      twenty = list.get(1).getThirdElement();
      

      【讨论】:

        【解决方案6】:

        您可以从列表中获取矩阵对象:

         Matrices m = list.get(0);// fist element in list
         m.anyPublicMethod();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-07
          • 2020-07-15
          • 2017-08-07
          • 2013-08-09
          • 2020-07-21
          相关资源
          最近更新 更多