Java Reference
In-Depth Information
if (part[h].getPrice() < part[small].getPrice()) small = h;
return small;
} //end getLowestPrice
If we were writing inside the class
Part
, we could leave the method as it is. But since we now have direct access to
the instance variables, we could replace the
if
statement with this one:
if (part[h].price < part[small].price) small = h;
To print the name of the part with the lowest price, we could write this:
System.out.printf("\nPart with lowest price: %s\n",
part[getLowestPrice(part, 0, part.length-1)].getName());
As an exercise, write a function to return the item with the highest price.
2.12 Searching an Array of Objects
We assume you know how to search for an item in an array of primitive types or an array of strings. Here, we consider
how to search an array of objects (more precisely, references to objects) with more than one field. For example,
suppose we had a
Person
class defined (partially) by the following:
public class Person {
String name;
int age;
char gender;
// constructors, static fields and other methods
} //end class Person
We want to search an array
person
containing objects of type
Person
for one with a given name,
key
. In the case
of searching for a primitive type or string, the type of the search key is the same as the type of elements in the array. In
the case of searching an array of objects with more than one field, the type of the search key is the same as
one of the
fields
of the object.
Our search method must compare
key
with the correct field. In this example, we compare
key
with
person[h].name
. The following method searches for a given name in an array of
Person
. We use
equalsIgnoreCase
so that case differences in the key and the array would not matter;
Mary
would be the same as
mary
.
// search for key in the first n elements of the array person;
// if found, return the position, else return -1
public static int sequentialSearch(String key, Person[] person, int n) {
for (int h = 0; h < n; h++)
if (key.equalsIgnoreCase(person[h].name)) return h;
return -1;
}
If we want to search for someone with a given
age
, we just need to declare
key
as
int
and change the
if
statement to this:
if (key == person[h].age) return h;
Search WWH ::
Custom Search