Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
class Inventory {
  private final Hashtable<String, Integer> items;
  public Inventory() {
    items = new Hashtable<String, Integer>();	
  }

  public List<String> getStock() {
    List<String> lstock = new ArrayList<String>();
    Enumeration eitemKeys = items.keys();
    while(eitemKeys.hasMoreElements()) {
      Object value = eitemKeys.nextElement();
      if((items.get(value)) == 0) {  		
        lstock.add((String)value);	 
      }
    }
    
    if(items.size() == 0) {	
      return null;
    } else {
      return lstock;
    }	
  }
}

public class Client {
  public static void main(String[] args) {
    Inventory ivinv = new Inventory();  
    List<String> items = ivinv.getStock();
    System.out.println(items.size()); // Throws a NPE
  }
}

...

Code Block
bgColor#ccccff
class Inventory {
  private final Hashtable<String, Integer> items;
  public Inventory() {
    items = new Hashtable<String, Integer>();	
  }

  public List<String> getStock() {
    List<String> lstock = new ArrayList<String>();
    Integer noOfItems; // Number of items left in the inventory
    Enumeration eitemKeys = items.keys();
    while(eitemkeys.hasMoreElements()) {
      Object value = eitemKeys.nextElement();
		
      if((noOfItems = items.get(value)) == 0) {  		
        lstock.add((String)value);	 
      }
    }	
    return lstock; // Return list (possibly zero-length)
  }
}

public class Client {
  public static void main(String[] args) {
    Inventory ivinv = new Inventory();  
    List<String> items = ivinv.getStock();
    System.out.println(items.size()); // Does not throw a NPE
  }
}

...

Code Block
bgColor#ccccff
public List<String> getStock() {
  List<String> lstock = new ArrayList<String>();
  Integer noOfItems; // Number of items left in the inventory
  Enumeration eitemkeys = items.keys();
  while(eitemkeys.hasMoreElements()) {
    Object value = eitemKeys.nextElement();
		
    if((noOfItems = items.get(value)) == 0) {  		
      lstock.add((String)value);	 
    }
  }	
  
  if(l.isEmpty()) {
    return Collections.EMPTY_LIST; // Always zero-length
  } else {
    return lstock; // Return list 
  }
}

// Class Client ...

...