Why does the following code dump a ClassCastException?
import java.util.*;
public class ClassLoader extends java.lang.ClassLoader
{
protected Set<Package> packages = new TreeSet<Package>();
public ClassLoader()
{
super();
loadPackageSet();
}
public Set getPackageSet()
{
return packages;
}
protected void loadPackageSet()
{
Package pkg[] = super.getPackages();
for ( int i = 0; i < pkg.length; i++ )
{
// Could catch the ClassCastException here, in which case the
// only package that actually makes it into the Set is
// java.lang. The other 127 packages dump the exception.
packages.add(pkg[i]);
}
}
}
Thanks,
Randall
Thomas Hawtin - 20 Mar 2006 19:15 GMT
> Why does the following code dump a ClassCastException?
> protected Set<Package> packages = new TreeSet<Package>();
"The elements are ordered using their natural ordering, or by a
Comparator provided at set creation time, depending on which constructor
is used."
-- http://download.java.net/jdk6/docs/api/java/util/TreeSet.html
[1] Link to java.lang.Comparable
http://download.java.net/jdk6/docs/api/java/lang/Comparable.html
java.lang.Package does not implement java.lang.Comparable.
Where you have a collection of a type that does not support Comparable,
you need to either supply your own Comparator (difficult/expensive if
there is no obvious ordering), or use a different implementation
(probably HashSet).
IMO, it's a bit daft having a single implementation try to cope with
both Comparable and Comparator. If it used static creation methods for
Comparable usage, then it wouldn't be a problem.
Tom Hawtin

Signature
Unemployed English Java programmer
http://jroller.com/page/tackline/
Roedy Green - 20 Mar 2006 19:40 GMT
> public Set getPackageSet()
> {
> return packages;
> }
one thing, that should read
public Set<Package> getPackageSet()

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 20 Mar 2006 19:59 GMT
>Package pkg[] = super.getPackages();
> for ( int i = 0; i < pkg.length; i++ )
[quoted text clipped - 4 lines]
> packages.add(pkg[i]);
> }
this code can be simplified to:
Package pkgs[] = super.getPackages();
for ( Package p: pkgs )
{
packages.add(p);
}
or even further to:
packages.addAll( Array.asList( super.getPackages() ) );

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
rwfields@yahoo.com - 21 Mar 2006 20:10 GMT
Thank you all for the intelligent feedback. With your suggestions
included:
import java.util.*;
public class ClassLoader extends java.lang.ClassLoader {
protected Set<Package> packages = new TreeSet<Package>(
new Comparator<Package>() {
public int compare(Package p1, Package p2) {
return p1.getName().compareTo(p2.getName());
}
}
);
public ClassLoader() {
super();
packages.addAll(Arrays.asList(super.getPackages()));
}
public Set<Package> getPackageSet() {
return packages;
}
}