Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Search an element of ArrayList with indexOf and lastIndexOf

import java.util.ArrayList; public class Main {   public static void main(String[] args) {     ArrayList<String> arrayList = new ArrayList<String>();     arrayList.add("2");     arrayList.add("3");     arrayList.add("4");     arrayList.add("5");     arrayList.add("1");     arrayList.add("2");     System.out.println(arrayList.contains("2"));     int index = arrayList.indexOf("4");     if (index == -1)       System.out.println("not contain 4");     else       System.out.println("4 at index :" + index);     int lastIndex = arrayList.lastIndexOf("1");     if (lastIndex == -1)       System.out.println("not contain 1");     else       System.out.println("Last index :"+ lastIndex);   } } /*true 4 at index :3 Last index :5 */