[英]In Java, how can I access an ArrayList of integer arrays
这是我的代码:
// create an arraylist of type integer array
ArrayList<int[]> timesTables = new ArrayList<>();
// add data
timesTables.add(new int[]{42, 17, 81});
timesTables.add(new int[]{1, 2, 3});
timesTables.add(new int[]{1000, 2000, 3000});
// this does not work
Log.i("Status ", timesTables.get((0)[0]).toString());
我知道这里的错误与我尝试使用 (0)[0] 引用数据的方式有关,但我无法弄清楚正确的语法。 我知道这有效:
Log.i("Status ", timesTables.get(0).toString());
但这仅给出数组地址(我认为),而不是数组的值,也不是一个数组中的单个值,这就是我正在尝试的。
次要问题:我试图查看文档来自己回答这个问题,但作为初学者,我不确定在哪里看。 我不知道我应该使用哪个网站或我应该查找哪一段代码(get、int[] 等)。
在此先感谢您的帮助。
您正在创建的是一个int 原始数组列表。
因此,使用 List 的get()方法通过索引获取要使用的数组,然后是获取的数组中目标条目的索引。
timesTables.get(0)[0]
您不能使用toString作为您希望打印的值是int 原始类型。
因此,对于您的具体问题,您可以执行以下操作:
Log.i("Status", Integer.toString(timesTables.get(0)[0]));
为了澄清一点你的疑问,更详细地说,上面的和下面的一样:
int[] array = timesTables.get(0); // Get by index an array from the list
int value = array[0]; // Get by index an int value from the obtained array
Log.i("Status", Integer.toString(value));
您不能放置空索引,因此您应该在写入(0)
时写入要访问的数组的名称。
// create an arraylist of type integer array
ArrayList<int[]> timesTables = new ArrayList<>();
// add data
timesTables.add(new int[]{42, 17, 81});
timesTables.add(new int[]{1, 2, 3});
timesTables.add(new int[]{1000, 2000, 3000});
// this does not work
Log.i("Status ", Integer.toString(timesTables.get(0)[0]));
您是正确的,因为这会打印 int 数组的对象引用。
Log.i("Status ", timesTables.get(0).toString());
如果要打印数组的内容,请使用Arrays.toString(...) ,例如:
Log.i("Status ", Arrays.toString(timesTables.get(0)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.