数组内的数组列表访问 [英] Array inside arraylist access
问题描述
我正在尝试访问作为数组中对象的一部分存储的变量.然而,该数组在一个数组列表中.如何访问该变量?为了清楚起见,我有一个有速度的汽车对象.我将 4 辆车放在一个数组中.并且该数组被复制并放入一个数组列表中.
I am trying to access a variable that is stores as part of an object that is in an array. However that array is in an arraylist. How can access that variable? To make it clear, I have a car object that has speed. I placed 4 cars in an array. And that array is duplicated and put in an arraylist.
public int getSpeedOfCarA (int index) {//used to access the variable speed in an array
return garage [index].getSpeed ();
}
现在我正在尝试这个,但卡住了.
Now I was trying this but got stuck.
public int getSpeedOfCarB(int n){
carSpeeds.get(...); //not sure what to use here.
}
推荐答案
要访问其他事物内部的事物,只需将访问语法链接在一起即可.对于在 List
内的数组内的对象内获取字段的示例,您只需使用
To access things inside of other things, simply chain the access syntax together. For the example of getting a field inside an object inside an array inside a List
, you would simply use
list.get(pos)[arrayPos].fieldName
然而,您可能误解了 ArrayList 的工作原理:在使用它时,您永远不会看到数组,实际上就语法而言,它是作为 Array 还是作为 LinkedList 或其他任何方式实现都无关紧要.如果是这样,您不需要使用任何数组运算符,因为 get
方法将为您完成:
You may be misunderstanding how ArrayList works however: When working with it, you never see the array, and in fact as far as syntax is concerned it doesn't matter whether it's implemented as an Array or as a LinkedList or whatever else. If so, you need not use any array operator, as the get
method will do that for you:
list.get(pos).fieldName
这篇关于数组内的数组列表访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!