SWE/CS 332 In Class Exercise # 15

Name(s):

Consider a variation of Liskov's IntSet example (Figure 5.10, page 97)
public class IntSet implements Cloneable {  
   private List<Integer> els;
   public IntSet () { els = new ArrayList<Integer>(); }
   ...
   @Override 
   public boolean equals(Object obj) {  // Standard recipe
      if (!(obj instanceof IntSet)) return false;

      IntSet s = (IntSet) obj;
      return ???
   }

   @Override 
   public int hashCode() { 
      // see below 
   }

   // adding a private constructor
   private IntSet (List<Integer> list) { els = list; }

   @Override 
   public IntSet clone() { 
      return new IntSet ( new ArrayList<Integer>(els));
   }
}

  1. How should the equals() method be completed?

  2. Analyze the following ways to implement hashCode()? If there is a problem, give a test case that shows the problem.
     
    0) not overridden at all
    
    1) return 42;
    
    2) return els.hashCode();
    
    3) int sum = 0;
       for (Integer i : els) sum += i.hashCode();
       return sum;
    
  3. Does the private constructor need to be private?



  4. Is the return type for clone() ok? What's the geeky term for this?



  5. Note that clone() doesn't use clone() on ArrayList. Could it? Any downside?



  6. What's the real problem with clone() here?



  7. Give a test case that shows the problem.



  8. Fix clone() by replacing its functionality in two very different ways. What are the advantages of the replacemnts over clone()?