Java Reference
In-Depth Information
product in the collection matches the product ID, iteration can finish and that first Product
object can be returned. On the other hand, it is possible that there might be no match in the
collection. In that case, the whole collection will be examined without finding a product to re-
turn. In this case, the null value should be returned.
When looking for a match, you will need to call the getID method on a Product .
Exercise 4.58 Implement the numberInStock method. This should locate a product in
the collection with a matching ID and return the current quantity of that product as a method
result. If no product with a matching ID is found, return zero. This is relatively simple to imple-
ment once the findProduct method has been completed. For instance, numberInStock
can call the findProduct method to do the searching and then call the getQuantity
method on the result. Take care over products that cannot be found, though.
Exercise 4.59 Implement the delivery method using a similar approach to that used in
numberInStock . It should find the product with the given ID in the list of products and then
call its increaseQuantity method.
Exercise 4.60 Challenge exercises Implement a method in StockManager to print details
of all products with stock levels below a given value (passed as a parameter to the method).
Modify the addProduct method so that a new product cannot be added to the product list
with the same ID as an existing one.
Add to StockManager a method that finds a product from its name rather than its ID:
public Product findProduct(String name)
In order to do this, you need to know that two String objects, s1 and s2 , can be tested for
equality with the boolean expression
s1.equals(s2)
More details can be found on this in Chapter 5.
4.15
Flexible-collection summary
We have seen that classes such as ArrayList conveniently allow us to create collections
containing an arbitrary number of objects. The Java library contains more collections like this,
and we shall look at some of the others in the next chapter. You will find that being able to use
collections confidently is an important skill in writing interesting programs. There is hardly an
application we shall see from now on that does not use collections of some form.
 
 
Search WWH ::




Custom Search