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> stock = new ArrayList<String>();
    Enumeration itemKeys = items.keys();
    while (itemKeys.hasMoreElements()) {
      Object value = itemKeys.nextElement();
      if((items.get(value)) == 0) {  		
        stock.add((String)value);	 
      }
    }
    
    if(items.size() == 0) {	
      return null;
    } else {
      return stock;
    }	
  }
}

public class Client {
  public static void main(String[] args) {
    Inventory inv = new Inventory();  
    List<String> items = inv.getStock();
    System.out.println(items.size()); // Throws an 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> stock = new ArrayList<String>();
    Integer noOfItems; // Number of items left in the inventory
    Enumeration itemKeys = items.keys();
    while (itemkeysitemKeys.hasMoreElements()) {
      Object value = itemKeys.nextElement();
		
      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()); // Does not throw an NPE
  }
}

...

Code Block
bgColor#ccccff
public List<String> getStock() {
  List<String> stock = new ArrayList<String>();
  Integer noOfItems; // Number of items left in the inventory
  Enumeration itemkeysitemKeys = items.keys();
  while (itemkeysitemKeys.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 {
    return stock; // Return list 
  }
}

// Class Client ...

...