positivevibesonly
positivevibesonly

Reputation: 3147

Android Arraylist find index

I have an ArrayList of object in my Fragment.

ArrayList<MenuListItem> menuItems = new ArrayList<MenuListItem>();
menuItems.add(new MenuListItem("Newsfeed", 20));
menuItems.add(new MenuListItem("FriendsRequest", 1));
menuItems.add(new MenuListItem("Messages", 2));

private class MenuListItem {
    public String label;
    public int count;

    public MenuListItem(String label, int count) {
        this.label = label;
        this.count = count;
    }
}

How can I find the index of object that has the label value "Messages" in my ArrayList from my Activity.

Upvotes: 2

Views: 7717

Answers (4)

Ragunath Jawahar
Ragunath Jawahar

Reputation: 19733

There's a easier and standard way to do this.

Eclipse

Right-click inside MenuListItem class and select Source -> Generate hashCode() and equals() once you are done generating the implementations of these methods. You can use ArrayList.indexOf(Object) to get the index of the item you are looking for.

IntelliJ or Android Studio

Right-click inside your editor and click on Generate and from the dialog that pops up, select hashCode() and equals().

The Collections framework has made things easier for you already. Why not leverage it instead of writing loops to find objects? :)

PS: This can be hand written, but this is something best left to the IDE. Because having too many attributes makes it tricky to get it right the first time.

Upvotes: 0

upog
upog

Reputation: 5526

try

        String search="Messages";
        for(int i=0;i<menuItems.size();i++){
            if(menuItems.get(i).label.equalsIgnoreCase(search)){
                System.out.println("Index " + i);
                break;
            }
        }

Upvotes: 3

Yaroslav Mytkalyk
Yaroslav Mytkalyk

Reputation: 17115

public static int indexOf(final List<MenuListItem> menuItems, final String what) {
    final int size = menuItems.size();
    for (int i = 0; i < size; i++) {
        final String label = menuItems.get(i).label;
        if (label != null && label.equals(what)) {
            return i;
        }
    }
    return -1;
}

Upvotes: 2

Алексей
Алексей

Reputation: 1847

have you try to iterate through elements of menuItems?

something of this sort:

for(MenuListItem menuListItem : menuItems){
    if (menuListItem.label.equals(<what you are looking for>){
        <do something>
        break; // in case when 1st occurence is sufficient
    }
}

side note (not related make your members private and add accessors for them)

Edit: just noticed that you are looking for an index, what i have included is to get an MenuListItem what you can do is iterate and return index if you want.

Upvotes: 4

Related Questions