Java 如何遍历Android ArrayList并获取索引
我有两个Java 如何遍历Android ArrayList并获取索引,java,android,arraylist,Java,Android,Arraylist,我有两个数组列表。我需要遍历stationNames数组并获取索引。然后返回stationId数组的相同索引的值。我如何做到这一点?请帮帮我。stackoverflow的现有解决方案对此不起作用。我是android开发新手 当我像下面的代码一样迭代数组时,它会给出一个错误,说Array-type-expected;找到:java.util.ArrayList ArrayList stationNames=new ArrayList(); ArrayList StationId=新的ArrayLi
数组列表
。我需要遍历stationNames
数组并获取索引。然后返回stationId
数组的相同索引的值。我如何做到这一点?请帮帮我。stackoverflow的现有解决方案对此不起作用。我是android开发新手
当我像下面的代码一样迭代数组时,它会给出一个错误,说Array-type-expected;找到:java.util.ArrayList
ArrayList stationNames=new ArrayList();
ArrayList StationId=新的ArrayList();
stationName=“你好”
int指数=-1;
试一试{
对于(int i=0;i
此处的stationNames不是数组,而是一个ArrayList
。因此,不能在其上使用.length
,请使用.size()
:
更简单的做法是:
return stationNames.indexOf(stationName);
如果在列表中找到,将返回其位置,否则返回-1。只需使用
ArrayList
对象的indexOf
方法即可
ArrayList<String> stationNames = new ArrayList<String>();
ArrayList<String> stationIDs = new ArrayList<String>();
String stationName = "Hello"
int index = stationNames. indexOf(stationName);
if(index!=-1){
String value= stationIDs[index];
}
ArrayList stationNames=new ArrayList();
ArrayList StationId=新的ArrayList();
String stationName=“你好”
int index=站点名称。indexOf(站点名称);
如果(索引!=-1){
字符串值=StationId[索引];
}
没有试扣和for循环的所有杂音。我可以用一行代码完成同样的任务,比如下面
int output = stationIDs.get(stationNames.indexOf(stationName));
谢谢大家的帮助 考虑从station name->station id创建地图,然后每个查找将是O(1)而不是O(n)
int output = stationIDs.get(stationNames.indexOf(stationName));