我知道遍历嵌套循环中的对象是一种不好的做法。我遇到过这样的情况,并且很难找到避免嵌套循环的方法。
我有一个项目清单。每个项目可以有多个位置。
> Item01 -> location01, location02, location03
> Item02 -> Location04, location05
....
我的代码如下所示
List<Item> itemList = getItemList();
RenderItem renderItem = new RenderItem();
List<RenderItem> renderItemList = new ArrayList<RenderItem>();
for (Item item: itemList){
for (ItemLocation itemLocation : item.getLocations() ){
renderItem = new RenderItem();
renderItem.setItem(item);
renderItem.setLocation(itemLocation);
renderItemList.add(renderItem);
}
}
我需要遍历所有位置并创建一个renderItemList。
如何摆脱嵌套循环?我应该使用什么策略?请指教。 [注意:我只能使用Java 7]
遍历嵌套循环中的对象是一种不好的做法
Nested Loop
是一种不好的做法,如果有另一种最佳解决方案可以减少从O(N^2)
或O(A*B)
到O(N)
的时间复杂度
但在你的情况下
你需要触摸所有Locations
中的所有Items
所以没问题
通过增加空间复杂性,您可以减少时间复杂度。如果你只是为了保存Locations而维护另一个ArrayList,那么它将需要更多的内存,但是你可以用单循环直接遍历Locations ArrayList。