更好的方式来寻找项目的索引中的ArrayList? [英] Better way to find index of item in ArrayList?

查看:123
本文介绍了更好的方式来寻找项目的索引中的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天全站免登陆