Si vous voulez obtenir le Index
de un élément spécifique dans un tableau, vous pouvez faire quelque chose comme ceci:
public static void main(String[] args){
// Create example Arrays
Integer[] arrayOfIntegers = {1,2,3,4,5};
String[] arrayOfStrings = {"A", "B", "C", "D",};
/******Test*******/
// what is the index of Integer 2 in the arrayOfIntegers
System.out.println(getIndex(arrayOfIntegers, 2));
// what is the index of String "C" in the arrayOfStrings
System.out.println(getIndex(arrayOfStrings, "C"));
// what is the index of String "X" in the arrayOfIStrings
// which doesn't exist (expected value is -1)
System.out.println(getIndex(arrayOfStrings, "X"));
}
/**
* This method to return the index of a given Object in
* the array. It returns - 1 if doesn't exist
* @param array
* @param obj
*/
public static int getIndex(Object[] array, Object obj){
for(int i=0; i<array.length; i++){
if(obj.equals(array[i])){
return i;
}
}
return -1;
}
sortie
1
2
-1
De plus, si vous voulez retourner TOUS Indices trouvés pour un répété élément dans un tableau, vous pouvez faire quelque chose comme ceci:
/**
* This method returns all indices of a given Object
* in an ArrayList (which will be empty if did not found any)
* @param array
* @param obj
*/
public static ArrayList<Integer> getIndices(Object[] array, Object obj){
ArrayList<Integer> indices = new ArrayList<Integer>();
for(int i=0; i<array.length; i++){
if(obj.equals(array[i])){
indices.add(i);
}
}
return indices;
}
Test
// Create example Array with duplicates
String[] arrayHasDuplicates = {"A", "B", "C", "D", "B", "Y", "B"};
System.out.println(getIndices(arrayHasDuplicates, "B"));
Output:
[1, 4, 6]
Je suis confus ce que vous essayez d'obtenir, si vous itérez à travers le tableau un à la fois, logiquement, l'indice de chaque itération sera le même que votre valeur «i» ... – Reed
@ Aominè ah, merci pour la clarification. – Reed