2013-06-24 41 views
-4

我是初學Java的人。我有3個ArrayLists,所有ArrayLists都包含與特定主題有關的數據,因此具有相同的長度。我想遍歷數組並執行一些操作,如下圖所示:使用相同索引遍歷多個數組列表

public void example(){ 
    ArrayList<Long> ID = new ArrayList<Long>; 
    ArrayList<Integer> AcNo = new ArrayList<Integer>; 
    ArrayList<Integer> Vnum = new ArrayList<Integer>; 

    //get ID and AcNo from user, compare it in the ArrayList, get the corresponding Vnum 
    // for the Vnum from previous step, compare it with the next Vnum and get corresponding ID and AcNo until some *condition* is satisfied. 

    } 

如何在Java中執行此操作?我看到了迭代器的例子,但我不確定這樣做的正確方法!請幫忙。

回答

2

如果所有三個列表的長度都相同,則使用對帶有索引的循環進行迭代。同樣的指標代表在三個名單相同的用戶:

for (int i=0; i<ID.size(); i++) { 
    Long userId= ID.get(i); 
    Integer userAcNo= AcNo.get(i); 
    Integer userVnum= Vnum.get(i); 

    //if the next user exist, get the next user 
    if (i + 1 < ID.size()) { 
     Long nextUserId= ID.get(i+1); 
     Integer nextUserAcNo= AcNo.get(i+1); 
     Integer nextUserVnum= Vnum.get(i+1); 

     //now compare userVariables and nextUser variables 
    } 
} 
2

一個更好的方法是將有物體或者類似的一個列表,讓每個主題包含本身的所有相關數據。

class Subject { 
    private final long id; 
    private final int acNo; 
    private final int vnum; 

    /* Appropriate constructor and getters... */ 
} 

您可能還想考慮重命名這些字段,以便它們更具描述性。