Java Reference
In-Depth Information
if ((noOfItems = items.get(value)) == 0) {
stock.add((String)value);
}
}
return stock; // Return list (possibly zero-length)
}
}
public class Client {
public static void main(String[] args) {
Inventory inv = new Inventory();
List<String> items = inv.getStock();
System.out.println(items.size());
}
}
The client can handle this situation effectively without being interrupted by runtime
exceptions. When returning arrays rather than collections, ensure that the client avoids at-
tempts to access individual elements of a zero-length array. This prevents an ArrayIn-
dexOutOfBoundsException from being thrown.
Compliant Solution
This compliant solution returns an explicit empty list, which is an equivalent permissible
technique.
Click here to view code image
public List<String> getStock() {
List<String> stock = new ArrayList<String>();
Integer noOfItems; // Number of items left in the inventory
Enumeration itemKeys = items.keys();
while (itemKeys.hasMoreElements()) {
Object value = itemKeys.nextElement();
if ((noOfItems = items.get(value)) == 0) {
stock.add((String)value);
}
}
if (l.isEmpty()) {
return Collections.EMPTY_LIST; // Always zero-length
} else {
Search WWH ::




Custom Search