繁体   English   中英

如何遍历对象的ArrayList?

[英]How to iterate through ArrayList of objects?

我有一个名为SparseMatrix的类。 它包含节点的ArrayList(也是类)。 我想知道如何遍历数组并访问Node中的值。 我尝试过以下方法:

 //Assume that the member variables in SparseMatrix and Node are fully defined.
 class SparseMatrix {
     ArrayList filled_data_ = new ArrayList();
     //Constructor, setter (both work)

     // The problem is that I seem to not be allowed to use the operator[] on
     // this type of array.
     int get (int row, int column) {
         for (int i = 0; i < filled_data_.size(); i++){
             if (row * max_row + column == filled_data[i].getLocation()) {
                 return filled_data[i].getSize();
             }
         }
         return defualt_value_;
     }
 }

我可能会切换到静态数组(并在每次添加对象时重新创建它)。 如果有人有解决方案,我非常感谢您与我分享。 另外,谢谢你提前帮助我。

如果您对此无法理解,请随时提出问题。

假设filled_data_是一个包含名为Node的类的对象列表的列表。

List<Nodes> filled_data_ = new ArrayList<>();
for (Node data : filled_data_) {
    data.getVariable1();
    data.getVariable2();
}

更多信息http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/

首先,您不应该使用原始类型。 有关详细信息,请参阅此链接: 什么是原始类型,为什么我们不应该使用它?

修复是声明数组列表所包含的对象类型。 将声明更改为:

 ArrayList<Node> filled_data_ = new ArrayList<>();

然后,您可以使用filled_data_.get(i)访问数组列表中的每个元素(而不是filled_data_[i] ,这将适用于常规数组)。

`filled_data_.get(i)`

以上将返回索引i处的元素。 文档: https//docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int)

如果您没有使用泛型,那么您需要转换对象

//Assume that the member variables in SparseMatrix and Node are fully defined.
 class SparseMatrix {
 ArrayList filled_data_ = new ArrayList();
 //Constructor, setter (both work)

 // The problem is that I seem to not be allowed to use the operator[] on
 // this type of array.
 int get (int row, int column) {
     for (int i = 0; i < filled_data_.size(); i++){
         Node node = (Node)filled_data.get(i);
         if (row * max_row + column == node.getLocation()) {
             return node.getSize();
         }
     }
     return defualt_value_;
 }

}

如果数组列表包含定义getLocation() Nodes ,则可以使用:

((Nodes)filled_data_.get(i)).getLocation()

你也可以定义

ArrayList<Nodes> filled_data_ = new ArrayList<Nodes>();

创建ArrayList对象时,应使用<>括号指定包含元素的类型。 保持对List接口的引用也很好 - 而不是ArrayList类。 要遍历这样的集合,请使用foreach循环:

以下是Node类的示例:

public class Node {
    private int value;

    public Node(int value) {
        this.value = value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

以下是Main类的示例:

public class Main {

    public static void main(String[] args) {

        List<Node> filledData = new ArrayList<Node>();
        filledData.add(new Node(1));
        filledData.add(new Node(2));
        filledData.add(new Node(3));

        for (Node n : filledData) {
            System.out.println(n.getValue());
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM