1

I have this two ArrayLists. I need to iterate through the stationNames Array and get the index. Then return the value of the same index of stationIDs array. How do i achieve this? Please help me. The existing solutions on stackoverflow didn't work on this. I am new to android development.

When i iterate through the Array like the following code it give an error saying Array type expected; found: java.util.ArrayList<java.lang.String>

ArrayList<String> stationNames = new ArrayList<String>();
ArrayList<String> stationIDs = new ArrayList<String>();

stationName = "Hello"

int index = -1;
try {
    for (int i = 0; i < stationNames.length; i++) {
        if (stationNames[i].equals(stationName)) {
            index = i;
            break;
        }
    }
}
catch (Exception e){
    Log.d("Excetion!",e.getLocalizedMessage());
}
return stationIDs[index];
1
  • Consider creating a map from station name -> station id, then each lookup will be O(1) instead of O(n) Commented Sep 17, 2017 at 8:00

3 Answers 3

3

stationNames here is not an array , but an ArrayList. So, you cannot use .length on it, use .size() :

Even simpler to do :

return stationNames.indexOf(stationName);

if it is found in the list will return its position or -1 if not.

Sign up to request clarification or add additional context in comments.

Comments

1

Without all the hazzle of try catches and for loops. I could do the same task with one line of code, like following...

int output = stationIDs.get(stationNames.indexOf(stationName));

Thank you all for your help!

Comments

-1

Just use indexOf method of the ArrayList object.

ArrayList<String> stationNames = new ArrayList<String>();
ArrayList<String> stationIDs = new ArrayList<String>();

String stationName = "Hello"

int index = stationNames. indexOf(stationName);

if(index!=-1){
 String value= stationIDs[index];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.