对于 Android 应用程序,我有以下功能
private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]
private int getCategoryPos(String category) {
for(int i = 0; i < this._categories.size(); ++i) {
if(this._categories.get(i) == category) return i;
}
return -1;
}
这是编写获取元素位置的函数的“最佳”方法吗?或者我应该利用java中的一个奇特的shmancy本机函数?
ArrayList
有一个 indexOf()
方法。检查 API 了解更多信息,但它的工作原理如下:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf()
将快速返回您的方法返回的内容。
ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index
int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
Log.e(TAG, "Object not found in List");
} else {
Log.i(TAG, "" + position);
}
输出:列表索引:7
如果您传递H,它将返回7,如果您传递J,它将返回-1,因为我们将默认值定义为-1。
完成
如果您的
List
已排序并且具有良好的随机访问性(如 ArrayList
那样),您应该查看 Collections.binarySearch
。否则,您应该使用 List.indexOf
,正如其他人指出的那样。
但是你的算法是合理的,fwiw(除了其他人指出的
==
)。
Java API 指定了两种可以使用的方法:
indexOf(Object obj)
和 lastIndexOf(Object obj)
。第一个返回元素的索引(如果找到),否则返回 -1。第二个返回最后一个索引,这就像向后搜索列表一样。
java 中确实有一个奇特的 shmancy 原生函数,你应该利用。
ArrayList 有一个名为
的实例方法indexOf(Object o)
(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)
您可以在
_categories
上调用它,如下所示:
_categories.indexOf("camels")
我没有 Android 编程经验 - 但这适用于标准 Java 应用程序。
祝你好运。
最好的解决方案在这里
class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
使用indexOf()方法查找集合中元素的第一次出现。
查找列表中项目位置的最佳方法是使用 Collections 接口,
例如,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
输出:2