2009-11-14 77 views
0

我在構造函數中創建for循環以同時迭代地圖和數組時遇到了一些麻煩。 Here,這表明這不能用增強for循環完成。在for循環中同時迭代地圖和數組

我有這樣的事情,這會引發編譯器錯誤。基本上,這個類有一個我想通過構造函數來填充的Map,它將一個集合和一個可變數目的整數作爲參數。

var-arg表達式求值爲一個整數數組,所以我試圖將兩個增強迭代器放在同一個循環中,但沒有奏效。

private final Map<Module, Integer> modules = new HashMap<Module, Integer>();  
    AssemblyType(Collection<Module> modules, int... units) { 
     int i = 0; 
     for (Module module : modules, int i : units) { 
      this.modules.put(module, units[i]); 
     }  
    } 

感謝您對如何着手的任何想法。

+0

&&操作符是否在for循環中工作? – 2009-11-14 03:34:38

回答

2

天真的方式做,這將只是跟蹤i自己:

private final Map modules = new HashMap();  
    AssemblyType(Collection modules, int... units) { 
     int i = 0; 
     for (Module module : modules) { 
       this.modules.put(ingredient, units[i]); 
       i++; 
     }    
    }

我不知道是否有更好的辦法,但我敢肯定你不能結合內部的兩個迭代器像您的原始示例一樣使用一個for循環。

+0

最簡單的方法通常是最好的。它也適用於這種情況,因爲var args與集合的長度相同!謝謝 – denchr 2009-11-14 03:44:51

0

它看起來像你試圖通過模塊Map作爲Collection這會導致編譯錯誤。

代碼以迭代都可能是這樣的

public MyMethod(Map<Object, Object> objectMap, Integer ... intArray) { 
    if(intArray.length != ObjectMap.size()) { 
     //However you want to handle this case 
    } 
    Iterator<Object> mapKeyIterator = objectMap.keySet().iterator(); 
    Iterator<Integer> integerIterator = Arrays.asList(intArray).iterator(); 

    while(mapKeyIterator.hasNext()) { //If the array and map are the same size then you only need to check for one. Otherwise you'll need to validate both iterators have a next 
     Object keyFromMap = mapKeyIterator.next(); 
     Object valueFromMap = objectMap.get(keyFromMap); 
     Integer intFromArray = integerIterator.next(); 
     //Whatever you want to do 
    } 
} 

如果你知道他們是相同的長度,那麼你也可以用一個for(int i ...循環遍歷數組,只需使用一個迭代的地圖,如果你不想創建一個List。

0

這似乎是一個非常容易出錯的API,要求完全斷開連接的地圖和數組。不僅容易出錯,但代碼的讀者很難判斷哪個int與哪個映射條目相關聯。我總是建議不要使用這種API。嘗試Map < Object,MySpecialType >其中MySpecialType聚合Object和int。

+0

是的,它可能有點風險。你介意給出一個簡短的例子,說明你所建議的方法 – denchr 2009-11-18 14:29:58

+0

這個問題如此模糊地陳述很難;如果你能使它更具體一點,這將有所幫助。 (注意:現在我的回答稍微容易理解,因爲我已經回到了正確的角度 - aughghghg。) – 2009-11-19 20:09:17