在 ArrayList 中查找项目索引的更好方法? [英] Better way to find index of item in ArrayList?

查看:19
本文介绍了在 ArrayList 中查找项目索引的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 Android 应用程序,我有以下功能

For an Android app, I have the following functionality

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 本机函数?

Is that the "best" way to write a function for getting an element's position? Or is there a fancy shmancy native function in java the I should leverage?

推荐答案

ArrayList 有一个 indexOf() 方法.查看 API 了解更多信息,但它的工作原理如下:

ArrayList has a indexOf() method. Check the API for more, but here's how it works:

private ArrayList<String> _categories; // Initialize all this stuff

private int getCategoryPos(String category) {
  return _categories.indexOf(category);
}

indexOf() 将快速返回您的方法返回的内容.

indexOf() will return exactly what your method returns, fast.

这篇关于在 ArrayList 中查找项目索引的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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