猿问

对于每个嵌套

我有一个表是主表,然后我有两个表(a,b)有主表的外键。我如何通过a table和b table示例进行检索:


table header is main id=1

然后在桌子a上插入one,比桌子b上插入两个one,two


我想要显示它由行one-one然后two-two但现在我通过显示了一个问题one-one,one-two,two-one,two-two我的朋友说,我必须使用HashMap的下面让我循环的代码不必要价值


//这是我的代码


ArrayList<Main>listMain = mainDAO.getlAllMain(Connection con);

for(Main listMain : listMain) {

  ArrayList<A> listA = aDAO.getallbyMainId(Connection con, int main);

  for(A listA : listA) {

    ArrayList<B> listB = bDAO.getallbyMainId(Connection con, int main);

    for(B listB : listB) {

      Main main = new Main();

      main.setMainName(listMain.getName());

      a.set(listA.getName);

      b.set(listB.getName);

    }

  }

}



鸿蒙传说
浏览 95回答 1
1回答

繁花不似锦

不应该在这里使用嵌套的for-each循环。尝试在上建立索引listMain,并将每次迭代的结果存储在一种元组中。该元组可以存储在中Map。如您的朋友所述,您可以HashMap为此使用a 。这样的事情应该可以解决问题:&nbsp; &nbsp; ArrayList<Main>listMain = mainDAO.getlAllMain(Connection con);&nbsp; &nbsp; Map<Integer, Pair<A, B>> map = new Hashmap<>();&nbsp; &nbsp; for (int i = 0; i < listMain.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp;ArrayList<A> listA = aDAO.getallbyMainId(Connection con, int main);&nbsp; &nbsp; &nbsp; &nbsp;ArrayList<B> listB = bDAO.getallbyMainId(Connection con, int main);&nbsp; &nbsp; &nbsp; &nbsp;A aValue = listA.get(i);&nbsp; &nbsp; &nbsp; &nbsp;B bValue = listB.get(i);&nbsp; &nbsp; &nbsp; &nbsp;map.put(i, new Pair(aValue, bValue));&nbsp; &nbsp; }我在这里使用apache-commons类Pair作为元组。参见下文以获取有关Java中元组的更多信息。例如,您可以为此使用自定义类。还可以String根据您稍后要使用的信息将配对内容的类型和映射键更改为a 。希望我能正确理解您的问题,并且此答案对您有所帮助。
随时随地看视频慕课网APP

相关分类

Java
我要回答