Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - get element position in array

Tags:

java

arraylist

I'm familiar with the ways I can get an element position in array, especially the ones showed here: Element position in array

But my problem is I can't figure out how to convert this code to fit my needs.

What I want to check is if a String has a match in an ArrayList and if so, what's the index of the String in the ArrayList.

The annoying part is I managed to verify the String is in the ArrayList (see first line of my code)

listPackages is the ArrayList

current_package is the String I want to find its position in listPackages.

Here's my code:

if (listPackages.contains(current_package)) {

        int position = -1;
        for(int j = 0; j < listPackages.size(); j++) {

            if(listPackages[j] == current_package) {
              position = j;
                  break;
              }
            }
    }

Would appreciate any help!

Thanks!

like image 607
Lior Iluz Avatar asked Sep 28 '11 09:09

Lior Iluz


3 Answers

Use indexOf:

int index = listPackages.indexOf(current_package); 

Note that you shouldn't generally use == to compare strings - that will compare references, i.e. whether the two values are references to the same object, rather than to equal strings. Instead, you should call equals(). That's probably what was going wrong with your existing code, but obviously using indexOf is a lot simpler.

like image 182
Jon Skeet Avatar answered Oct 03 '22 22:10

Jon Skeet


just use the call listPackages.indexOf(current_package);

ArrayList.contains(Object o) calls indexOf(Object o) internally in ArrayList:

/**
 * Returns <tt>true</tt> if this list contains the specified element.
 * More formally, returns <tt>true</tt> if and only if this list contains
 * at least one element <tt>e</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
 *
 * @param o element whose presence in this list is to be tested
 * @return <tt>true</tt> if this list contains the specified element
 */
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
like image 28
mcfinnigan Avatar answered Oct 03 '22 23:10

mcfinnigan


Hope this will help you.change your code like this:

if (listPackages.contains(current_package)){
int position=listPackages.indexOf(current_package);
}

Also if you will make position variable as global you can access its value outside this block of code. :)

like image 25
Android Killer Avatar answered Oct 03 '22 23:10

Android Killer