Re: Newbie question: Can a parameterized container hold objects
derived from the parameter?
On May 23, 11:52 am, mrstephengross <mrstevegr...@gmail.com> wrote:
I have two classes: Base and Derived (where Derived extends Base). I
also have a Set parameterized on Base (Set<Base>). Can I add a Derived
instance to my set?
The following code demonstrates this, and causes a ClassCastException:
class Base {};
clase Derived {};
I assume you mean class Derived extends Base {} here. Also, Java does
not require semicolons after class declarations.
Set<Base> set = new TreeSet<Base>();
set.add(new Derived()); // <-- Causes exception
The ClassCastException here has nothing to do with the relationship
between Base and Derived (and as written the error would be a compile-
time error about incorrect types; see previous remark about
'extends' :). TreeSet requires that either the elements themselves
implement Comparable or that you provide a Comparator at construction
time. If you don't provide a Comparator, it tries to cast elements to
Comparable when inserting them -- and since neither Base nor Derived
implements Comparable, this causes the CCE you're encountering.
Unless you need a set that's sorted, try another Set implementation
like HashSet that doesn't impose extra constraints on the contents.
If you do need a sorted set, make sure there's something to sort on!
Either make Base implement Comparable (correctly) or provide an
implementation of Comparator for Base when constructing the TreeSet.
-o