Java - get element position in array

后端 未结 4 1854
谎友^
谎友^ 2021-01-03 20:47

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

相关标签:
4条回答
  • 2021-01-03 21:25

    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;
    }
    
    0 讨论(0)
  • 2021-01-03 21:41

    use the indexof method to get the position -

    listPackages.indexOf(current_package)
    

    http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)

    0 讨论(0)
  • 2021-01-03 21:46

    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.

    0 讨论(0)
  • 2021-01-03 21:52

    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. :)

    0 讨论(0)
提交回复
热议问题