首页 > 解决方案 > 由于索引超出范围,对“get”的调用总是无法索引

问题描述

我希望我不是在这里写一个重复的问题,我试图查找它,但我没有找到任何东西。

所以我有一个名为 Map 的类,我尝试为它配置我的生成器函数,以便它接受参数 ListOfLocations 以及另外两个整数宽度和高度。

还有另一个名为 Places 的类,我在其中给出位置列表中的坐标并创建一个实例。第三个处理坐标。

public class Map {

     private ArrayList <ArrayList<Places>> newMap = new ArrayList<>();

     public Map(int width, int height, Collection <Coordinate> places){   
             //Create places
    for (int i=0;i<=width-1;i++){
        for (int j=0;j<=height-1;j++){
            newMap.get(i).add(new Place(new Coordinate(i,j)));
        }
    } 

这个想法是它遍历所有组合(i,j)它创建一个坐标并将该坐标传递给类 Place。因为我有我的 Map 作为 ArrayLists 的 ArrayList(我希望它是 2D 的)我尝试用.get调用一个字段

前任。当它处理宽度i时,它应该在位置i上获取列表并添加一个新位置。

但我得到一个

由于索引超出范围,对“get”的调用总是失败。

同样的情况也发生在我有.get电话的另外两个地方。

有人可以向我解释我的错误在哪里吗?

提前致谢 :)

标签: java

解决方案


您初始化列表但从不填充它:

// The List is not null but is actually empty
private ArrayList <ArrayList<Places>> newMap = new ArrayList<>();

因此,newMap.get(0)没有意义。你得到一个空列表的第一个元素。

你可以这样做:

public class Map {

  private ArrayList <ArrayList<Places>> newMap = new ArrayList<>();

  public Map(int width, int height, Collection <Coordinate> places){

    for (int i=0;i<=width-1;i++){
      ArrayList<Places> list = new ArrayList<Places>();
      for (int j=0;j<=height-1;j++){
        list.add(new Place(new Coordinate(i,j)));
      }
      newMap.add(list);
    } 

一些建议:

  • 不要调用你的类Map,已经有一个使用这个名字的类,它会带来一些混乱。
  • 声明列表时,最好将其声明为List(接口),而不是ArrayList(实际实现)。

像这样 :

private List<List<Places>> newMap = new ArrayList<>();

推荐阅读