2016-10-08 47 views
5

我有一个名为SparseMatrix的类。它包含节点的ArrayList(也是类)。我想知道如何迭代Array并访问Node中的值。我试过以下内容:如何遍历对象的ArrayList?

//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_; 
    } 
} 

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

如果您在这里不了解任何内容,请随时提问。

+1

您应该使用泛型,并且不能使用[i]从ArrayList中获取元素,则必须使用.get(i)。 –

回答

2

首先,你不应该使用原始类型。请参阅此链接以获取更多信息:What is a raw type and why shouldn't we use it?

修复的方法是声明数组列表中的对象类型。更改声明:

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)

+0

这有助于很多,谢谢。 (我有使用C++的经验,所以Java概念对我来说是相当新的。)我发现了一种用静态数组来做到这一点的方法(效率低下),所以我会考虑到这一点。再次感谢您的帮助。 – sudomeacat

+0

@diuqSehTnettiK没问题=] – nhouser9

1

如果你没有使用通用的,那么你就需要把对象

//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_; 
} 

}

+0

听起来很有趣,请提供您的意思的例子。 – sudomeacat

0

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

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

你也可以定义

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

当您创建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; 
    } 
} 

这里是主类的一个实例:

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()); 
     } 
    } 
}