Как найти индекс элемента в массиве int? - PullRequest
72 голосов
/ 30 мая 2011

Как найти индекс определенного значения в массиве Java типа int?

Я пытался использовать Arrays.binarySearch в моем несортированном массиве, только иногда он дает правильный ответ.

Ответы [ 16 ]

0 голосов
/ 22 мая 2018
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;
    }
}
0 голосов
/ 13 апреля 2018

Если кто-то все еще ищет ответ -

  1. Вы можете использовать ArrayUtils.indexOf () из [Библиотеки Apache Commons] [1].

  2. Если вы используете Java 8, вы также можете использовать Strean API:

    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[],%20int)

0 голосов
/ 10 ноября 2017

В основном методе, использующем для циклов: - третий цикл for в моем примере - это ответ на этот вопрос. -в моем примере я сделал массив из 20 случайных целых чисел, присвоил переменной наименьшее число и остановил цикл, когда местоположение массива достигло наименьшего значения при подсчете количества циклов.

import java.util.Random;
public class scratch {
    public static void main(String[] 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 == <smallest>
                break;
            }
            location ++;
        }
        System.out.println("location: " + location + "\nsmallest: " + smallest);
    }
}

Код выводит все числа и их местоположения, а также местоположение наименьшего номера, за которым следует наименьшее число.

0 голосов
/ 04 июля 2013
/**
     * 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 голосов
/ 04 мая 2013

Вы можете сделать это так:

 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(String[] 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;

}

}

Добавлен XOR:)

0 голосов
/ 30 мая 2011

Вы можете либо пройти по массиву, пока не найдете искомый индекс, либо использовать вместо него List.Обратите внимание, что вы можете преобразовать массив в список с помощью asList().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...