ArrayLists and Iterators
16. Searching for an Element
Answer:
Case A:true
Case B:false
Case C:true
Case D:false
Case E:true
Case A: the list starts out empty, so isEmpty()
returns true.
Case B: the value null
has been added to the list, and is now held at index zero. isEmpty()
returns false.
Case C: the value at index zero has been removed from the list. isEmpty()
returns true.
Case D: a reference to a string has been added to the list at index zero. The string happens to be the empty string, but it is a legitimate object and the cell at index zero holds a reference to it. isEmpty()
returns false.
Case E: clear()
has made the list empty. isEmpty()
returns true.
Searching for an Element
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 ofelement
.
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.* ;
public 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( "First Search: " + names.indexOf( "Elaine" ) );
System.out.println( "Secnd Search: " + names.indexOf( "Zoe" ) );
}
}