在获取一个ArrayList的项目的索引; [英] Getting Index of an item in an arraylist;
问题描述
我有一个名为类 AuctionItem
。在 AuctionItem
类有一个方法的getName()
返回一个字符串
。如果我有一个的ArrayList
类型 AuctionItem
,什么是返回一个项目的索引中的最佳方式的ArrayList
有一个特定的名称?
I have a Class called AuctionItem
. The AuctionItem
Class has a method called getName()
that returns a String
. If I have an ArrayList
of type AuctionItem
, what is the best way to return the index of an item in the ArrayList
that has a specific name?
我知道有一个 .indexOf()
功能。这个函数的参数是一个对象。要找到具有名称的项目,应我只是用一个for循环,当项目被找到,返回元素位置的的ArrayList
?
I know that there is an .indexOf()
function. The parameter for this function is an object. To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList
?
有没有更好的办法?
推荐答案
我觉得一个for循环应该是一个有效的解决方案:
I think a for-loop should be a valid solution :
public int getIndexByname(String pName)
{
for(AuctionItem _item : *yourArray*)
{
if(_item.getName().equals(pName))
return *yourarray*.indexOf(_item)
}
return -1;
}
这篇关于在获取一个ArrayList的项目的索引;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!