Reputation: 179
I want tofind the index of the custom array list. This is my custom array list:
private ArrayList<UserData> ListItems = new ArrayList<>();
UserData list = new UserData("list", "5", R.drawable.email_black, false);
UserData list1 = new UserData("list1", "3",R.drawable.text_msg, false);
UserData list2 = new UserData("list2", "2",R.drawable.phone_call, false);
ListItems.add(list);
ListItems.add(list1);
ListItems.add(list2);
I am doing like below but not getting the index .
int m = ListItems.indexOf("list1");
UserData obj = ListItems.get(m);
String name = obj.getName();
I need list1 in name string.
Upvotes: 3
Views: 2469
Reputation: 3456
In such a scenario, You can use HashMap also. Use HashMap<String,UserData>
where String would be "list", "list1" etc.
Ex -
map.put("list", list);
Upvotes: 1
Reputation: 2608
Iterator your array list to get your required data. Do something like below:
for (int i = 0; i < ListItems.size(); i++) {
String userListName = ListItems.get(i).getListName();
if(userListName.equals("list1")){
//Do something here
}else{
//Nthng to do
}
}
Upvotes: 3
Reputation: 311326
The indexOf
method is based on the argument and the item in the list being equal. Since they are not (one is a UserData
instance and the other is a String
), you can't use indexOf
. Instead, you'll have to implement this logic yourself:
private UserData getUserDataByName(String name) {
for (UserData item : listItems) {
if (item.getName().equals(name)) {
return item;
}
}
// Not found, return null;
return null;
}
Upvotes: 1