简体   繁体   English

Java中2D数组类型的ArrayList

[英]ArrayList of type 2D array in Java

I have declared an ArrayList along the lines of this at the beginning of my code: 我在代码的开头声明了一个ArrayList:

ArrayList<int[][]> arraylists = new ArrayList<>();

Since Netbeans is not giving me an error, I am assuming that syntax wise, this is a valid declaration. 由于Netbeans没有给我一个错误,因此我假设该语法是明智的,这是一个有效的声明。

I added a 2D array element like this: 我添加了一个2D数组元素,如下所示:

int[][] newarray = {{0},{0}};
arraylists.add(newarray);

I called upon the ArrayList like so: 我这样调用ArrayList:

int[][] array = arraylists.get(0);

Since I have already added something to the ArrayList, I will not get an index out of bounds exception. 由于我已经向ArrayList添加了一些内容,因此不会出现索引超出范围的异常。

However, it is not getting the 2D Array at index 0. To debug I tried doing this: 但是,它没有在索引0处获得2D数组。要调试,我尝试这样做:

System.out.println("testing");
int[][] array = arraylists.get(0);

The output is this: testing 输出是这样的: testing

However, when I tried doing this: 但是,当我尝试这样做时:

int[][] array = arraylists.get(0);
System.out.println("testing");

The output is nothing 输出什么都没有

I think this means that there is a problem with getting the 2D array within the ArrayList as no other error pops up. 我认为这意味着在ArrayList中获取2D数组存在问题,因为没有其他错误弹出。 I think it would be good to mention that nothing else after getting the 2D array from the ArrayList works. 我认为最好是从ArrayList获取2D数组后再进行其他操作。 So the program stop there. 因此程序在此停止。 I am just beginning my code so this is just about all I have so far, and I plan on continuing the code once this problem is resolved. 我刚刚开始编写代码,所以这几乎是我到目前为止所拥有的一切,并且计划解决此问题后继续编写代码。 Note that Netbeans is not alerting me saying that there is anything wrong. 请注意,Netbeans并没有提醒我说有什么问题。 It just isn't working... 只是不起作用...

Can anyone help me to identify what is wrong? 谁能帮助我找出问题所在?

Probably just Netbeans being silly. 可能只是Netbeans愚蠢。 Try cleaning the project and rebuild. 尝试清理项目并重建。 This code works just fine: 这段代码可以正常工作:

public static void main(String[] args) {
    List<int[][]> list = new ArrayList<>();
    list.add(new int[][]{{1,2}, {3,4}});
    int[][] twoD = list.get(0);
    System.out.println(Arrays.deepToString(twoD));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM