Can you tell me if there is a method for searching for elements in the array? PS search will be conducted in an array of char elements

    3 answers 3

    Convert the array to a list and call indexOf() on the list.

     char[] data = {'a', 'c', 'b'}; int idx = Arrays.asList(data).indexOf('b'); 

    And if the array is sorted, then it is better to call Arrays.binarySearch()

     char[] data = {'a', 'b', 'c'}; int idx = Arrays.binarySearch(data, 'b'); 

      Alas, there is nothing standard in java, you have to write your bikes:

        private static int find(char[] array, char element) { if (Objects.isNull(array)) return -1; for (int i = 0; i < array.length; i++) if (array[i] == element) return i; return -1; } 

      Alternatively, you can use the Apache Commons Lang library, there is a utility class ArrayUtils with the indexOf method

      • There are Arrays.binarySearch() for sorted arrays - Anton Shchyrov
      • Well, yes, but the question is not about sorted arrays - Artem Konovalov
      • one
        There is nothing in the question about sorting - Anton Shchyrov

      You can try this:

       private static int findChar(char[] array, char element) { return new String(array).indexOf(element); } 

      Returns either the position of the character in the array, or -1 if absent.