问题描述
限时送ChatGPT账号..我有一个名为 AuctionItem
的类.AuctionItem
类有一个名为 getName()
的方法,它返回一个 String
.如果我有一个 AuctionItem
类型的 ArrayList
,返回具有特定名称的 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;
}
这篇关于获取数组列表中项目的索引;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论