Determine the position of an element in an array. - Android java.lang

Android examples for java.lang:Array Element

Description

Determine the position of an element in an array.

Demo Code


//package com.java2s;

public class Main {
    /**// ww  w  .j a  va  2s .  c  o  m
     * Determine the position of an element in an array.
     * 
     * @param <T> the type of the element.
     * @param array the array.
     * @param s the element.
     * @return the index of {@code s} in {@code array}, or -1 if not found.
     */
    public static <T> int indexOf(T[] array, T s) {
        if (null == array) {
            return -1;
        }
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(s)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Determine the position of an element in an array.
     * 
     * @param <T> the type of the element.
     * @param array the array.
     * @param s the element.
     * @return the index of {@code s} in {@code array}, or -1 if not found.
     */
    public static int indexOf(int[] array, int s) {
        if (null == array) {
            return -1;
        }
        for (int i = 0; i < array.length; i++) {
            if (array[i] == s) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Determine the position of an element in an array.
     * 
     * @param <T> the type of the element.
     * @param array the array.
     * @param s the element.
     * @return the index of {@code s} in {@code array}, or -1 if not found.
     */
    public static long indexOf(long[] array, long s) {
        if (null == array) {
            return -1;
        }
        for (int i = 0; i < array.length; i++) {
            if (array[i] == s) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Checks if the beginnings of two byte arrays are equal.
     * 
     * @param array1 the first byte array
     * @param array2 the second byte array
     * @param length the number of bytes to check
     * @return true if they're equal, false otherwise
     */
    public static boolean equals(byte[] array1, byte[] array2, int length) {
        if (array1 == array2) {
            return true;
        }
        if (array1 == null || array2 == null || array1.length < length
                || array2.length < length) {
            return false;
        }
        for (int i = 0; i < length; i++) {
            if (array1[i] != array2[i]) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials