¿Cómo encontrar el índice de un elemento en un array en Java?


Estoy buscando encontrar el índice de un elemento dado, conociendo su contenido, en Java.

Probé el siguiente ejemplo, que no funciona:

class masi { 
    public static void main( String[] args ) { 
        char[] list = {'m', 'e', 'y'};

        // should print 1
        System.out.println(list[] == "e");                    
    } 
}

¿Puede alguien explicar qué tiene de malo esto y qué tengo que hacer para arreglarlo?

Author: Bart Kiers, 2009-10-06

14 answers

En este caso, puede crear e nueva cadena a partir de su matriz de caracteres y luego hacer un indeoxOf ("e") en esa cadena:

System.out.println(new String(list).indexOf("e")); 

Pero en otros casos de tipos de datos primitivos, tendrás que iterar sobre ellos.

 43
Author: Bart Kiers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-05 20:07:42

Esa sintaxis ni siquiera es válida. Y estás tratando de comparar con una cadena. Para los arrays tendrías que recorrer el array tú mismo:

public class T {
  public static void main( String args[] ) {
    char[] list = {'m', 'e', 'y'};

    int index = -1;

    for (int i = 0; (i < list.length) && (index == -1); i++) {
        if (list[i] == 'e') {
            index = i;
        }
    }

    System.out.println(index);
  }
}

Si está utilizando una colección, como ArrayList<Character> también puede usar el método indexOf():

ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');

System.out.println(list.indexOf('e'));

También existe la clase Arrays que acorta el código anterior:

List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));
 17
Author: Joey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-05 20:16:02

Alternativamente, puede usar Commons Lang ArrayUtils clase:

int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);

Hay variantes sobrecargadas del método indexOf() para diferentes tipos de matriz.

 13
Author: Max77,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-19 18:24:50

Para matrices primitivas

Comenzando con Java 8, la solución de propósito general para una matriz primitiva arr, y un valor para buscar val, es:

public static int indexOf(char[] arr, char val) {
    return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}

Este código crea un flujo sobre los índices de la matriz con IntStream.range, filtra los índices para mantener solo aquellos donde el elemento de la matriz en ese índice es igual al valor buscado y finalmente mantiene el primero emparejado con findFirst. findFirst devuelve un OptionalInt, como es posible que no se encontraron índices coincidentes. Así que invocamos orElse(-1) para devolver el valor encontrado o -1 si no se encontró ninguno.

Se pueden agregar sobrecargas para int[], long[], etc. El cuerpo del método seguirá siendo el mismo.

Para matrices de objetos

Para los arrays de objetos, como String[], podríamos usar la misma idea y tener el paso de filtrado usando el equals método, o Objects.equals para considerar dos nullelementos iguales, en lugar de ==.

Pero podemos hacerlo de una manera más simple con:

public static <T> int indexOf(T[] arr, T val) {
    return Arrays.asList(arr).indexOf(val);
}

Esto crea un contenedor de lista para la matriz de entrada utilizando Arrays.asList y busca el índice del elemento con indexOf.

Esta solución no funciona para arrays primitivos, como se muestra aquí : un array primitivo como int[] no es un Object[] sino un Object; como tal, invocando asList en él crea una lista de un solo elemento, que es el array dado, no una lista de los elementos de la matriz.

 8
Author: Tunaki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:34

Creo que la única manera más sana de hacer esto es iterar manualmente a través de la matriz.

for (int i = 0; i < list.length; i++) {
  if (list[i] == 'e') {
    System.out.println(i);
    break;
  }
}
 7
Author: Matt Solnit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-05 21:07:49

El problema con su código es que cuando lo hace

 list[] == "e"

Estás preguntando si el objeto array (no el contenido) es igual a la cadena "e", lo cual claramente no es el caso.

Usted querrá iterar sobre el contenido con el fin de hacer la comprobación que desea:

 for(String element : list) {
      if (element.equals("e")) {
           // do something here
      }
 }
 4
Author: Peter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-05 20:10:01

Ahora imprime 1

class Masi {
    public static void main( String [] args ) {
         char [] list = { 'm', 'e', 'y' };

         // Prints 1
         System.out.println( indexOf( 'e', list ) );
    }

    private static int indexOf( char c , char [] arr ) {
        for( int i = 0 ; i < arr.length ; i++ ) {
            if( arr[i] == c ) { 
                return i;
            }
         }
         return -1;
     }
 }

Tenga en cuenta que

"e"

Es un literal de objeto de cadena (que representa un objeto de cadena que es )

Mientras que

" e "

Es un carácter literal (que representa un tipo de datos primitivo de carácter)

Incluso cuando

list[]

Sería válido Java ( que no lo es ) comparar el elemento a character con un elemento string devolvería false de todos modos.

Simplemente use esa función indexOf string y podría encontrar cualquier carácter dentro de cualquier alfabeto ( o matriz de caracteres )

 2
Author: OscarRyz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-05 23:35:26

Muy Editado. Creo que o quieres esto:

class CharStorage {
    /** set offset to 1 if you want b=1, o=2, y=3 instead of b=0... */
    private final int offset=0;
    private int array[]=new int[26];

    /** Call this with up to 26 characters to initialize the array.  For 
      * instance, if you pass "boy" it will init to b=0,o=1,y=2.
      */
    void init(String s) {
        for(int i=0;i<s.length;i++)
            store(s.charAt(i)-'a' + offset,i); 
    }

    void store(char ch, int value) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        array[ch-'a']=value;
    }

    int get(char ch) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        return array[ch-'a'];
    }
}

(Tenga en cuenta que es posible que tenga que ajustar el método init si desea usar 1-26 en lugar de 0-25)

O quieres esto:

int getLetterPossitionInAlphabet(char c) {
    return c - 'a' + 1
}

El segundo es si siempre quieres a=1, z=26. El primero te permitirá poner una cadena como "qwerty" y asignar q=0, w=1, e=2, r=3...

 1
Author: Bill K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-05 23:30:32

De esta manera debería funcionar, cambiar "char" a "Character":

public static void main(String[] args){
  Character[] list = {'m', 'e', 'y'};
  System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}
 1
Author: Kehe CAI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-02 12:48:56

La solución más simple :

Convierta el array a list y podrá obtener la posición de un elemento.

List<String> abcd  = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");

Otra solución , puede iterador array:

int position = 0;
for (String obj : yourArray) {
    if (obj.equals("abcd") {
    return position;
    }
    position += 1;
} 

//OR
for (int i = 0; i < yourArray.length; i++) {
    if (obj.equals("abcd") {
       return i;
    }
}
 1
Author: MeosCoder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-08 16:14:13

Aquí hay otro ejemplo y cómo funciona indexOf.

public int indexOf(Object target) {
    for (int i = 0; i < array.length; i++) {
        if (equals(target, array[i])) {
            return i;
        }
    }
    return -1;
}
 1
Author: Salvador Vigo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-17 16:40:36

Si el orden inicial de los elementos no es realmente importante, simplemente podría ordenar el array, entonces binarySearch:

import java.util.Arrays;

class masi { 
    public static void main( String[] args ) { 
        char[] list = {'m', 'e', 'y'};
        Arrays.sort(list);

        // should print 0, as e is now sorted to the beginning
        // returns negative number if the result isn't found
        System.out.println( Arrays.binarySearch(list, 'e') );
    } 
}
 0
Author: Powerlord,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-05 21:22:06

Estoy proporcionando el método adecuado para hacer esto

/**
     * Method to get the index of the given item from the list
     * @param stringArray
     * @param name
     * @return index of the item if item exists else return -1
     */
    public static int getIndexOfItemInArray(String[] stringArray, String name) {
        if (stringArray != null && stringArray.length > 0) {
            ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
            int index = list.indexOf(name);
            list.clear();
            return index;
        }
        return -1;
    }
 0
Author: Manmohan Soni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-03 05:28:33

De esta manera puedes usar upto 'N' letters.

char[] a={ 'a', 'b', 'c', 'd', 'e' };
int indexOf=0;
for(int i=0;i<a.length;i++){
  if(a[i] != 'b'){
    indexOf++;
    }else{
    System.out.println("index of given: "+indexOf);
 }}
 -1
Author: Roshini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-29 04:21:12