Comment trouver l’index d’un élément dans un tableau int?

Comment puis-je trouver un index d’une certaine valeur dans un tableau Java de type int ?

J’ai essayé d’utiliser Arrays.binarySearch sur mon tableau non sortingé, cela donne parfois la réponse correcte.

 Integer[] array = {1,2,3,4,5,6}; Arrays.asList(array).indexOf(4); 

Notez que cette solution est threadsafe car elle crée un nouvel object de type List.

En outre, vous ne voulez pas invoquer ceci dans une boucle ou quelque chose comme ça puisque vous créez un nouvel object à chaque fois

Une autre option si vous utilisez les collections de goyave est Ints.indexOf

 // Perfect storm: final int needle = 42; final int[] haystack = [1, 2, 3, 42]; // Spoiler alert: index == 3 final int index = Ints.indexOf(haystack, needle); 

C’est un excellent choix lorsque l’espace, le temps et la réutilisation du code sont essentiels. C’est aussi très laconique.

Un coup d’oeil à l’ API et il dit que vous devez d’abord sortinger le tableau

Alors:

 Arrays.sort(array); Arrays.binarySearch(array, value); 

Si vous ne voulez pas sortinger le tableau:

 public int find(double[] array, double value) { for(int i=0; i 

Copie cette méthode dans ta classe

  public int getArrayIndex(int[] arr,int value) { int k=0; for(int i=0;i 

Appelez cette méthode avec pass deux perameters Array et value et stockez sa valeur de retour dans une variable entière.

 int indexNum = getArrayIndex(array,value); 

Je vous remercie

Vous pouvez le convertir en une liste, puis utiliser la méthode indexOf:

 Array.asList(array).indexOf(1); 

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#asList(T …) http://download.oracle.com/javase/1.5.0 /docs/api/java/util/List.html#indexOf(java.lang.Object )

Vous devez sortinger les valeurs avant d’utiliser la recherche binary. Sinon, la méthode manuelle consiste à essayer tous les ints de votre onglet.

 public int getIndexOf( int toSearch, int[] tab ) { for( int i=0; i< tab.length ; i ++ ) if( tab[ i ] == toSearch) return i; return -1; }//met 

Une autre méthode pourrait consister à mapper tous les index pour chaque valeur dans une carte.

 tab[ index ] = value; if( map.get( value) == null || map.get( value) > index ) map.put( value, index ); 

puis map.get (value) pour obtenir l'index.

Cordialement, Stéphane

@pst, merci pour vos commentaires. Pouvez-vous poster une autre méthode alternative?

Simple:

 public int getArrayIndex(int[] arr,int value) { for(int i=0;i 

Vous pouvez parcourir le tableau jusqu’à ce que vous trouviez l’index recherché ou utiliser une List place. Notez que vous pouvez transformer le tableau en une liste avec asList() .

 /** * Method to get the index of the given item from the list * @param ssortingngArray * @param name * @return index of the item if item exists else return -1 */ public static int getIndexOfItemInArray(Ssortingng[] ssortingngArray, Ssortingng name) { if (ssortingngArray != null && ssortingngArray.length > 0) { ArrayList list = new ArrayList(Arrays.asList(ssortingngArray)); int index = list.indexOf(name); list.clear(); return index; } return -1; } 

Vous pouvez le faire comme ceci:

  public class Test { public static int Tab[] = {33,44,55,66,7,88,44,11,23,45,32,12,95}; public static int search = 23; public static void main(Ssortingng[] args) { long stop = 0; long time = 0; long start = 0; start = System.nanoTime(); int index = getIndexOf(search,Tab); stop = System.nanoTime(); time = stop - start; System.out.println("equal to took in nano seconds ="+time); System.out.println("Index of searched value is: "+index); System.out.println("De value of Tab with searched index is: "+Tab[index]); System.out.println("=========================================================="); start = System.nanoTime(); int Bindex = bitSearch(search,Tab); stop = System.nanoTime(); time = stop - start; System.out.println("Binary search took nano seconds ="+time); System.out.println("Index of searched value is: "+Bindex); System.out.println("De value of Tab with searched index is: "+Tab[Bindex]); } public static int getIndexOf( int toSearch, int[] tab ){ int i = 0; while(!(tab[i] == toSearch) ) { i++; } return i; // or return tab[i]; } public static int bitSearch(int toSearch, int[] tab){ int i = 0; for(;(toSearch^tab[i])!=0;i++){ } return i; } 

}

Ajout d’un XOR 🙂

Dans la méthode principale utilisant pour les boucles: -le troisième pour la boucle dans mon exemple est la réponse à cette question. -dans mon exemple, j’ai créé un tableau de 20 nombres entiers aléatoires, assigné une variable dont le plus petit nombre et arrêté la boucle lorsque l’emplacement du tableau a atteint la plus petite valeur tout en comptant le nombre de boucles.

 import java.util.Random; public class scratch { public static void main(Ssortingng[] args){ Random rnd = new Random(); int randomIntegers[] = new int[20]; double smallest = randomIntegers[0]; int location = 0; for(int i = 0; i < randomIntegers.length; i++){ // fills array with random integers randomIntegers[i] = rnd.nextInt(99) + 1; System.out.println(" --" + i + "-- " + randomIntegers[i]); } for (int i = 0; i < randomIntegers.length; i++){ // get the location of smallest number in the array if(randomIntegers[i] < smallest){ smallest = randomIntegers[i]; } } for (int i = 0; i < randomIntegers.length; i++){ if(randomIntegers[i] == smallest){ //break the loop when array location value ==  break; } location ++; } System.out.println("location: " + location + "\nsmallest: " + smallest); } } 

Le code génère tous les numéros et leurs emplacements, ainsi que l’emplacement du plus petit nombre suivi du plus petit nombre.

Si quelqu’un cherche toujours la réponse –

  1. Vous pouvez utiliser ArrayUtils.indexOf () à partir de [Apache Commons Library] [1].

  2. Si vous utilisez Java 8, vous pouvez également utiliser l’API Strean:

     public static int indexOf(int[] array, int valueToFind) { if (array == null) { return -1; } return IntStream.range(0, array.length) .filter(i -> valueToFind == array[i]) .findFirst() .orElse(-1); } 

    [1]: https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#indexOf(int%5B%5D,%20int)

 Integer[] array = {1, 2, 3, 4, 5, 6}; for (int i = 0; i < array.length; i++) { if (array[i] == 4) { system.out.println(i); break; } }