get index of element in list java code example
Example 1: ArrayList indexOf(Object o) method in java
import java.util.ArrayList;
public class ArrayListIndexOfMethodExample
{
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>(5);
al.add(8);
al.add(6);
al.add(5);
al.add(7);
al.add(9);
System.out.print("ArrayList values are: ");
for(Integer num : al)
{
System.out.print(num);
System.out.print(" ");
}
int position = al.indexOf(5);
System.out.println("\nElement 5 is at index: " + position);
}
}
Example 2: get index of element in array java
System.out.println(new String(list).indexOf("e"));
Example 3: get index of an array element java
public class Exercise6 {
public static int findIndex (int[] my_array, int t) {
if (my_array == null) return -1;
int len = my_array.length;
int i = 0;
while (i < len) {
if (my_array[i] == t) return i;
else i=i+1;
}
return -1;
}
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
System.out.println("Index position of 25 is: " + findIndex(my_array, 25));
System.out.println("Index position of 77 is: " + findIndex(my_array, 77));
}
}