Java Reference
In-Depth Information
class Person{
String firstname, lastname; // key for searching
String phone; // additional fields go here
// Constructor
Person(String l, String f, String p)
{this.firstname=f; this.lastname=l; this.phone=p;}
};
Let us consider the keys of objects as the
lastname
and
firstname
attributes,
and report the phone number record of the object in case the object is found
in the array. The sequential search algorithm is implemented by the following
LinearSearch
function:
Program 6.2
Linear search on objects
static
Person []
array=
new
Person[5];
static
String LinearSearch(String lastname , String firstname)
for
(
int
i=0;i
<
array . length ; i++)
{
if
(( lastname . equals ( array [ i ] . lastname) &&
(firstname . equals(array [ i ]. firstname))))
{
return
array [ i ] . phone ;
}
return
"Not found in my dictionary"
;
}
Observe that the predicate for checking whether the keys of the current object
with the given query is not a single
==
comparison test but rather uses the
String
method
equals
to check that the string contents are identical. The
program below demonstrates the sequential search on an array of
Person
initialized. Observe that the array is defined as a
static
array so that its
data are attached to the program class and can therefore be accessed from the
various
static
functions of the class.
Program 6.3
A demonstration program using the
Person
object array
class
LinearSearchProgram
{
static
Person []
array=
new
Person[5];
static
String LinearSearch(String lastname , String
firstname)
{
...
}
public static void
main ( String [ ] args )
{
array [0]=
new
Person(
"Nielsen"
,
"Frank"
,
"0169364089"
);
array [1]=
new
Person(
"Nelson"
,
"Franck"
,
"04227745221"
);
array [2]=
new
Person(
"Durand"
,
"Paul"
,
"0381846245"
);
array [3]=
new
Person(
"Dupond"
,
"Jean"
,
"0256234512"
);
Search WWH ::
Custom Search