数组在arraylist访问中 [英] Array inside arraylist access

查看:71
本文介绍了数组在arraylist访问中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问一个变量,该变量存储为数组中对象的一部分.但是,该数组在arraylist中.如何访问该变量? 为了明确起见,我有一个具有速度的汽车对象.我将4辆汽车排成一排.然后该数组被复制并放入arraylist中.

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

这篇关于数组在arraylist访问中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆