0

コンストラクター内で 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]);
        }       
    }

続行する方法についてのアイデアをありがとう。

4

3 に答える 3

2

The naive way to do this would just be to track i yourself:

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++;
        }               
    }

I'm not sure if there's a better way, but I'm pretty sure you can't combine two iterators inside a single for loop like your original example.

于 2009-11-14T03:37:55.630 に答える
0

これは、完全に切断されたマップと配列を要求するため、非常にエラーが発生しやすい API のようです。エラーが発生しやすいだけでなく、コードの読者がどの int がどのマップ エントリに対応しているかを判断するのが難しくなります。私は常に、この種の API に反対することをお勧めします。MySpecialType が Object と int の両方を集約する Map<Object, MySpecialType> を試してください。

于 2009-11-18T08:21:44.427 に答える
0

It looks like your trying to pass a the modules Map as a Collection which would cause a compile error.

Code to iterate over both could be something like this

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
   }
}

If you know they are the same length then you could also traverse the array with a for(int i ... loop and just use an iterator for the map if you didn't want to create a List.

于 2009-11-14T03:38:22.273 に答える