Kushan
Kushan

Reputation: 59

how to get index of particular value in array list in android

I implement a bean class and then I create arraylist like below example.But I couldn't get index in particular name.I want to know how to search where employee name = “xxx” in array List in android.

eg:- let say I have a bean employee {name, number}

and have a arra list -> "array_list type is employee "

need to search where employee name = “xxx” in array list How I implement it? thanks!!!

Upvotes: 1

Views: 12002

Answers (3)

gabbar0x
gabbar0x

Reputation: 4266

Zahan's answer is right. However, the complexity of looking up an element in an ArrayList is O(n).

However, seeing the description, I think what you are looking for is a Map.

What a Map does, is stores information corresponding to a particular key. For example, I can have the Employee ID numbers as the key and the corresponding name of that employee as the value. You can read more about the tutorial I have written here or the generic one here.

I must mention that Map in JAVA is an Interface, so to implement it, you can use the HashMap class (uses hashing) which offers Amortized O(1) lookup time which is what you want to be shooting for.

Here is the implementation for storing the Employee id numbers as the key and the employoee names as the value. I must also mention that keys in a Map must always be unique. You will learn all this in the tutorial. I will assume that you have the Employee names and id numbers stored in an array of objects of class 'employee'. Here goes:

    employee[] data=new employee[100];
    /*code in this to store in this whatever data you have to
     */
    Map<Integer, String> lookupEmpName=new HashMap<Integer, String>();
    for(int i=0;i<data.length;i++)
        lookupEmpName.put(data[i].getEmpNumber,data[i].getName); //Store the key as the number and the name as the value
    String name=lookupEmpName.get(1234); //name will store the corresponding name of the employee if it exists or stores null


I hope this is what you were looking for. I'd be gald to help you out

Upvotes: 1

Zahan Safallwa
Zahan Safallwa

Reputation: 3914

You can use the method IndexOf() of java.util.ArrayList

An implementation is like

ArrayList<String> arrlist = new ArrayList<String>(5);
// use add() method to add values in the list
arrlist.add("G");
arrlist.add("E");
arrlist.add("F");
arrlist.add("M");


  // retrieving the index of element "E"

int retval=arrlist.IndexOf("E");

So, retval is the index of your desired object

Upvotes: 5

Harish Vats
Harish Vats

Reputation: 662

You can start a for loop on the arrayList. For each index get the employee object from list and from that object get the employee name. Compare this name with xxx and if it matches, store that value of i in some variable and break the loop.

Upvotes: 1

Related Questions