标记的行给我编译错误?

时间:2016-02-25 19:32:50

标签: java arrays arraylist

public void generateMap(ArrayList<NonPlayableFighter> weakFoes, ArrayList<NonPlayableFighter>
strongFoes){
    Map[0][0]=new FoeCell(strongFoes[(int)(Math.random()*8)]);
    for(int i=0;i<15;i++){
        Map[(int)(Math.random()*9)][(int)(Math.random()*9)]=new FoeCell(weakFoes[(int)(Math.random()*7)]);
    }
    Random rand;
    int randomNum = rand.nextInt((5 - 3) + 1) + 3;
    for(int i=0;i<randomNum;i++){
        Map[(int)(Math.random()*9)][(int)(Math.random()*9)].equals(Collectible.SENZU_BEAN); 
    }
    Map[(int)(Math.random()*9)][(int)(Math.random()*9)].equals(Collectible.DRAGON_BALL);
}

1 个答案:

答案 0 :(得分:1)

该行

Map[0][0]=new FoeCell(strongFoes[(int)(Math.random()*8)]);

因为您在strongFoes[somenumber]上使用数组访问表示法(方括号:ArrayList)而无法编译。 ArrayList不是数组,而是List。您无法使用[],您必须在get(someNumber)set(someNumber, someObject)上调用方法。

该特定代码行应该是这样的:

Map[0][0]=new FoeCell(strongFoes.get((int)(Math.random()*8)));

如果ArrayIndexOutOfBoundsException中没有足够的元素,您可以获得List

有关如何使用ArrayList的详细信息,请参阅http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html