java get index of item in arraylist code example

Example 1: java arraylist

import java.util.List; //list abstract class
import java.util.ArrayList; //arraylist class

//Object Lists
List l = new ArrayList();
ArrayList a = new ArrayList();

//Specialized List
List<String> l = new ArrayList<String>();
ArrayList<Integer> a = new ArrayList<Integer>();
//only reference data types allowed in brackets <>

//Initial Capacity
List<Double> l = new ArrayList<Double>(5);
//list will start with a capacity of 5
//saves allocation times

Example 2: arraylist java methds

import java.util.ArrayList;
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(0);
myList.remove(0);//Remove at index 0
myList.size();
myList.get(0);//Return element at index 0

Example 3: 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(" ");
      }
      // indexOf() method to find index of 5
      int position = al.indexOf(5);
      System.out.println("\nElement 5 is at index: " + position);
   }
}

Example 4: arraylist get value at index java

get(index);

Tags:

Java Example