Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Index of an item in an arraylist;

Tags:

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?

like image 722
user2351151 Avatar asked May 06 '13 07:05

user2351151


People also ask

Can we get index in ArrayList?

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.

How do you get the index of an item in a list in Java?

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.

How do you retrieve an element from a particular position of an ArrayList?

An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.


1 Answers

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;
    }
like image 121
Kooki Avatar answered Sep 29 '22 11:09

Kooki