我有这两个ArrayLists
.我需要遍历 stationNames
数组并获取索引。然后返回stationIDs
的同一个索引的值大批。我如何实现这一目标?请帮我。 stackoverflow 上的现有解决方案对此不起作用。我是 android 开发的新手。
当我像下面的代码一样遍历数组时,它给出一个错误提示 Array type expected; found: java.util.ArrayList<java.lang.String>
ArrayList<String> stationNames = new ArrayList<String>();
ArrayList<String> stationIDs = new ArrayList<String>();
stationName = "Hello"
int index = -1;
try {
for (int i = 0; i < stationNames.length; i++) {
if (stationNames[i].equals(stationName)) {
index = i;
break;
}
}
}
catch (Exception e){
Log.d("Excetion!",e.getLocalizedMessage());
}
return stationIDs[index];
最佳答案
这里的stationNames不是一个数组,而是一个ArrayList
。所以,你不能在上面使用 .length
,使用 .size()
:
做起来更简单:
return stationNames.indexOf(stationName);
如果在列表中找到则返回它的位置,否则返回-1。
关于java - 如何遍历 Android ArrayList 并获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46261782/