2016-10-08 45 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()); 
     } 
    } 
}