【问题标题】:Java, accessing element of ArrayList of ArrayListJava,访问ArrayList的ArrayList的元素
【发布时间】:2014-10-14 22:48:11
【问题描述】:

我确实看过Accessing ArrayList<ArrayList<SomeObject>> elements,但我认为在我的情况下有一个更简单的答案。还查看了Why does Java ArrayList use per-element casting instead of per-array casting?,这似乎解释了潜在的演员问题,但并不能帮助我了解这里的最佳方法。感谢您抽出宝贵时间阅读本文!

最终,我是一名 Java 新手,只是想实现一个 Map 类,该类将基于文本的 2-d 映射读取到某些数据结构中。因为我在阅读之前不知道地图大小,所以我尝试了 Vectors,但移到了 ArrayLists。

编辑这里的“地图”

12 12
MwwwppppffffMMMM
MMwwppppfffffMMM
MMMwwwwwppppffff
ffffMMMMMwwwpppp
ffffMMMMMwwwpppM
MwwwppfMMMMppfff
MwwwpffffMMMMppp
MwwwppppffffMMMM
wwppppffffMMMMMw
wppppffffMMMMMww
ppppffffMMMMMwww
pppffffMMMMMwwwp

我在方法之外有这个,就在类声明下:

// we have this vector here to be accessible to all methods
// the inner vector will be built in the readMapFile method
static private ArrayList mapList = new ArrayList();

然后在我有的readMapFile方法中(整个方法在最后):

        for ( int i = 0; i < mapRows ; ++i)
            {
                // read each subsequent line in the file
                mapFileLine = fileIn.nextLine();

                ArrayList mapRowList = new ArrayList();

                for ( int j = 0 ; j < mapCols ; ++j )
                {
                    // read each character on the line
                    mapRowList.add(mapFileLine.charAt(j));
                }

                // now put mapRowVector as an element of mapVector
                mapList.add(mapRowList); 

                System.out.println(mapList.get(i));

            }

然后我在尝试访问内部 ArrayList 中的元素时遇到了麻烦。有了这个我得到“对象不能被转换成 ArrayList:

public static char getTerrainAtLocation( int row, int column )
{

    ArrayList innerList = mapList.get(row);
    return innerList[column];
}

在我尝试运行它之前不会出错:

public static char getTerrainAtLocation( int row, int column )
{

    char[] innerList = (char[])mapList.get(row);
    return innerList[column];
}

我显然需要一些帮助!您在这里最好的建议是什么,我只想从“地图”中返回 x 行和 y 列的字符。我收到此错误:

Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to [C
at adventure2.Map.getTerrainAtLocation(Map.java:144)
at adventure2.Map.printMapList(Map.java:154)
at adventure2.Map.main(Map.java:56)
Java Result: 1

这是我完整的 readMapFile:

public static void readMapFile( String arg )
{
    if ( arg != "")
    {
        try
        {
            // open a path to the file given in arg 0, this won't throw
            // an exception
            Scanner fileIn = new Scanner(Paths.get(arg));

            // need to clear mapVector for the new file, if it already
            // has data in it
            mapList.clear();

            // this is the line that will throw the exception
            // try to read the file, see if it throws IOException
            mapRows = fileIn.nextInt();
            mapCols = fileIn.nextInt();

            // read to the end of line
            String mapFileLine = fileIn.nextLine();

            // now we have the first line read, with rows and columns
            // need a 2-D char array to hold the map
            //char[][] mapArray = new char [mapRows][mapCols];

            // make up the row vectors row by row, when a row is complete,
            // add that to the full Vector, making a Vector of Vectors

            for ( int i = 0; i < mapRows ; ++i)
            {
                // read each subsequent line in the file
                mapFileLine = fileIn.nextLine();

                ArrayList mapRowList = new ArrayList();

                for ( int j = 0 ; j < mapCols ; ++j )
                {
                    // read each character on the line
                    mapRowList.add(mapFileLine.charAt(j));
                }

                // now put mapRowVector as an element of mapVector
                mapList.add(mapRowList); 

                System.out.println(mapList.get(i));

            }
        }
        catch ( IOException e )
        {
            System.out.println("There was an error reading the file sorry!");
        }
    }
    else
    {
        // arg length was 0 or negative
        System.out.println("Must call readMapFile with a filename as argument");
    } 
} // end readMapFile

谢谢!

【问题讨论】:

  • FWIW 我把地图文字放在上面
  • 你到处都在使用原始类型,你应该使用类型参数。
  • 八月,我几乎不明白,你指的是调用ArrayList模板时会发生什么?我知道一些 C++,但对 Java 很陌生。
  • 1) 带有泛型的原始类型每次都会把你引向这个兔子洞。具体输入您的ArrayList。 2) 你是在尝试ArrayList&lt;ArrayList&lt;Character&gt;&gt;吗?
  • mapList.get(row) 不返回 ArrayList。它返回存储在该索引处的 ArrayList 的元素。

标签: java arrays arraylist casting


【解决方案1】:

Java 的数据结构很棒,但你必须记住基础知识 :)

class Terrain {

    private byte[] terrainData;
    private int terrainSizeX;
    private int terrainSizeY;

    public void init() {
        terrainData = new byte[terrainSizeX * terrainSizeY];
    }

    private int getIndex(int row, int column) {
        return terrainSizeX * column + row;
    }

    public byte getTerrainAtLocation(int row, int column) {
        return terrainData[getIndex(row, column)];
    }

    public void setTerrainAtLocation(int row, int column, byte value) {
        terrainData[getIndex(row, column)] = value;
    }
}

【讨论】:

  • 谢谢我太新了,不能投票。非常酷,它应该是 Java 中的高级编程类(后 C# 和 C++),但我从未想过使用字节数组,这很酷! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 2015-06-07
  • 2020-07-21
  • 2013-08-09
相关资源
最近更新 更多