Package ClassCastException

R

rwfields

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);
}
}
}

Thanks,
Randall
 
T

Thomas Hawtin

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
 
R

Roedy Green

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);
}


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() ) );
 
R

rwfields

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;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top