-4

我是Java的初学者。我有 3 个 ArrayList,所有 ArrayList 都包含与特定主题有关的数据,因此长度相同。我想遍历数组并执行一些操作,如下图所示:

  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 中做到这一点?我看到了 Iterator 的示例,但我不确定执行此操作的正确方法!请帮忙。

4

2 回答 2

2

如果所有三个列表的长度相同,则使用带有索引的 for 循环遍历它们。相同的索引代表三个列表中的每一个中的相同用户:

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
    }
}
于 2013-06-24T12:55:30.507 回答
2

更好的方法是拥有一个 Subject 对象或类似对象的列表,以便每个 Subject 包含有关其自身的所有相关数据。

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

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

您可能还需要考虑重命名这些字段,以便它们更具描述性。

于 2013-06-24T13:00:16.027 回答