【问题标题】:How can I find the index of an array element? [duplicate]如何找到数组元素的索引? [复制]
【发布时间】:2012-11-24 00:06:05
【问题描述】:

我有这个类,它在首选输入后显示数组的值:

class MyArrayList {

private int [] myArray;
private int size;

public MyArrayList (int value, int seed, int inc){

    myArray = new int [value];
    size = value;
    for (int i = 0; i < size; i++) {
        myArray [i] = seed;
        seed += inc;        
    }       
}   

}

public class JavaApp1 {

    public static void main(String[] args) {
        MyArrayList a = new MyArrayList(5, 2, 1);
        a.printList();

}
}

此程序显示以下输出: 2 3 4 5 6 现在我想找到 4 的索引,所以这将是 2 但我怎样才能将它放入程序中?

【问题讨论】:

    标签: java indexing


    【解决方案1】:

    循环获取值,然后你就有了索引,你可能希望它作为 MyArrayList 类的一个函数

        int[] myArray = {2,3,4,5,6};
        for (int i = 0; i < myArray.length; i++) 
        {
            if( myArray[i] == 4 )
                System.out.println( "index=" + i);
        }
    

    【讨论】:

    • +1,因为此答案将打印所查询项目的 所有 次出现。 OP 对于预期的内容模棱两可,但这种方法似乎更聪明。
    • 非常感谢您,先生,虽然这段代码实际上不起作用,至少我知道如何去做。
    【解决方案2】:

    您需要在MyArrayList 类中编写一个方法,该方法获取您要查找的值,并将其定位在数组中。要找到它,只需遍历数组,直到值匹配。

    这样的……

    public int findIndexOf(int value){
        for (int i=0; i<size; i++) {
            if (myArray[i] == value){
                return i;
            }
        }    
        return -1; // not found   
    }   
    

    现在您需要在 JavaApp1 类中调用这个新方法,它应该返回索引。

    【讨论】:

    • 您可能还需要记住,这不一定是唯一属性。
    • 嗯,是的,这可能会导致问题,但 OP 需要澄清他希望如何处理这种情况。目前它将返回第一个匹配的索引。
    【解决方案3】:

    Java 最好的部分之一是它是开源的,您可以查看所有标准 API 的源代码。

    这就是 ArrayList.indexOf(Object) 方法的工作原理:

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
        if (elementData[i]==null)
            return i;
    } else {
        for (int i = 0; i < size; i++)
        if (o.equals(elementData[i]))
            return i;
    }
    return -1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2019-11-16
      • 2011-06-25
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多