Thursday 26 July 2012

Search elements of LinkedList Java example


This java example shows how to search element of Java LinkedList using contains, indexOf and lastIndexOf methods.


import java.util.LinkedList;

public class SearchElementLinkedListExample {

 public static void main(String[] args) {

  // create LinkedList object
  LinkedList lList = new LinkedList();

  // add elements to LinkedList
  lList.add("1");
  lList.add("2");
  lList.add("3");
  lList.add("4");
  lList.add("5");
  lList.add("2");

  /**
   * To check if a particular element exists in a LinkedList, use boolean
   * contains(Object obj) method.
   * 
   * This method returns true if LinkedList contains a particular element,
   * false otherwise.
   **/

  boolean blnElement = lList.contains("4");

  if (blnElement) {
   System.out.println("LinkedList contains 4");
  } else {
   System.out.println("LinkedList does not contain 4");
  }

  /**
   * To search first occurrence of an element of LinkedList, use int
   * indexOf(Object element) method.
   * 
   * This method returns index of first occurrence of element if found in
   * the LinkedList. It returns -1 if element not found.
   **/

  int index = lList.indexOf("2");
  if (index != -1) {
   System.out
     .println("First occurrence of 2 in LinkedList is at index : "
       + index);
  } else {
   System.out.println("LinkedList does not contain 2");
  }

  /**
   * To search last occurrence of an element of LinkedList, use int
   * lastIndexOf(Object element) method.
   * 
   * This method returns index of last occurrence of element if found in
   * the LinkedList. It returns -1 if element not found.
   **/

  index = lList.lastIndexOf("2");
  if (index != -1) {
   System.out
     .println("Last occurrence of 2 in LinkedList is at index : "
       + index);
  } else {
   System.out.println("LinkedList does not contain 2");
  }

 }
}


The output is:



LinkedList contains 4
First occurrence of 2 in LinkedList is at index : 1
Last occurrence of 2 in LinkedList is at index : 5

No comments:

Post a Comment