Java arraylist search element example

import java.util.ArrayList;
import java.util.List;

/*
 * Here we will learn to search for element in ArrayList
 */
public class SearchElementINArrayList {

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();

		/*
		 * add() method appends the specified element to the end of given list.
		 */
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(5);
		list.add(6);

		/*
		 * indexOf(Object o) method returns the index of the first occurrence of
		 * the specified element in list, or -1 if this list does not contain
		 * the element.
		 * 
		 * Note*: Starting Index of List is 0
		 */
		System.out.println("Index of Element 5(Should be 4): "+ list.indexOf(5));
		System.out.println("nIndex of Element 77(Should be -1) as there is no element with such value in list");
		System.out.println(list.indexOf(77));

	}
}

 

By | 2012-09-18T13:45:47+00:00 September 18th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment