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));
}
}
- How should the
equals()
method be completed?
- 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;
- Does the private constructor need to be private?
- Is the return type for
clone()
ok? What's the
geeky term for this?
- Note that
clone()
doesn't use clone()
on ArrayList
. Could it? Any downside?
- What's the real problem with
clone()
here?
- Give a test case that shows the problem.
- Fix
clone()
by replacing its
functionality in two very different ways.
What are the advantages of the replacemnts over clone()
?