Searching for an Element

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Linear Search

Searching for an Element

Linear search starts at the first element and examines elements one by one until the target element is found. You could write linear search for an ArrayList but there is a method that does this for you:

int indexOf(Object element)    //  Search for the first occurrence of 
                               //  element, testing for equality 
                               //  using the equals(Object) method of element. 

The method returns the index of the first occurrence of element or -1 if element is not found.

QUESTION 16:

Examine the following program. What will it print?


import java.util.* ;
class SearchEg
{
  public static void main ( String[] args)
  {
    ArrayList<String> names = new ArrayList<String>();

    names.add( "Amy" );     names.add( "Bob" );
    names.add( "Chris" );   names.add( "Deb" );
    names.add( "Elaine" );  names.add( "Joe" );

    System.out.println( names.indexOf( "Elaine" ) ); 
    System.out.println( names.indexOf( "Zoe" ) ); 
  }
}