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?
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
?
Is there a better way?
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list.
The standard solution to find the index of an element in a List is using the indexOf() method. It returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.
An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With