1.Basic java Example program to search an element  ArrayList.

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  
  4. public class SearchArrayList{
  5.  
  6. public static void main(String[] args) {
  7.   
  8. //create an ArrayList object
  9.  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  10.        
  11.         //Add elements to Arraylist
  12.         arrayList.add(1);
  13.         arrayList.add(2);
  14.         arrayList.add(3);
  15.         arrayList.add(4);
  16.         arrayList.add(5);
  17.         arrayList.add(6);
  18.         arrayList.add(7);
  19.         arrayList.add(8);
  20.         arrayList.add(9);
  21.         arrayList.add(10);
  22.         
  23.  /*
  24.  To check whether the specified element exists in Java ArrayList use
  25. boolean contains(Object element) method.
  26. It returns true if the ArrayList contains the specified object, false
  27. otherwise.*/
  28.        
  29.         boolean isFound = arrayList.contains(2);
  30.         System.out.println("Does arrayList contain 2 ? " + isFound);
  31.      
  32.   /*
  33.    To get an index of specified element in ArrayList use
  34.    int indexOf(Object element) method.
  35.    This method returns the index of the specified element in ArrayList.
  36.    It returns -1 if not found.
  37.   */
  38.    
  39.    int index = arrayList.indexOf(11);
  40.  
  41.  if(index == -1)
  42.     System.out.println("ArrayList does not contain 11");
  43.   else
  44.     System.out.println("ArrayList contains 4 at index :" + index);
  45.         
  46.         
  47.    int secindex = arrayList.indexOf(5);
  48.  
  49.  if(secindex== -1)
  50.       System.out.println("ArrayList does not contain 5");
  51.  else
  52.      System.out.println("ArrayList contains 5 at index :" + secindex);
  53.        
  54.  System.out.println("Size of ArrayList: "+ arrayList.size()); 
  55.  
  56.  Iterator itr=arrayList.iterator();
  57.  
  58. while (itr.hasNext()) {
  59.  
  60.  System.out.println(itr.next());
  61.  
  62.  }
  63.   
  64. }
  65. }
     



Output:

  1. Does arrayList contain 2 ? true
  2. ArrayList does not contain 11
  3. ArrayList contains 5 at index :4
  4. Size of ArrayList: 10
  5. 1
  6. 2
  7. 3
  8. 4
  9. 5
  10. 6
  11. 7
  12. 8
  13. 9
  14. 10

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu