It's not a secret anymore!
The moose likes Beginning Java and the fly likes please help, class casting problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "please help, class casting problem" Watch "please help, class casting problem" New topic

please help, class casting problem

Josh Wetzel

Joined: Sep 30, 2000
Posts: 3
I'm having a lot of difficulty casting from one type to antother. My code compiles but I get a class cast exception error at runtime. Can anyone tell me why? Thanks in advance!!
import java.util.*;
public class SetPlusTest {
public static void main(String[] args) {
SetPlus s1 = (SetPlus) new HashSet();

for(int i=0; i<=4; i++) {
s1.add(new Integer(i));

SetPlus s2 = (SetPlus) new HashSet();
for(int i=0; i<=8; i+=2) {
s2.add(new Integer(i));
Set u = s1.union(s2);
System.out.println(s1 + " union " + s2 + " is " + u);
import java.util.*;
interface SetPlus extends Set {
SetPlus union(SetPlus s2);
import java.util.*;
public class HashSetPlus extends HashSet implements SetPlus {
public SetPlus union(SetPlus s2) {
SetPlus z = new SetPlus(s2);
return z;
Andy Ceponis
Ranch Hand

Joined: Dec 20, 2000
Posts: 782
Well your file 1 class name is SetPlusTest, but everywhere else you refer to it as SetPlus. You cant cast anything with a class that doesnt exist. Unless SetPlus is a class that im unaware of which it might be...
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Try thinking 'is a'.
It is NOT valid to say that a HashSet IS A SetPlus.
A HashSetPlus IS A SetPlus, but a HashSet is not.
Therefore what you want is:

or thereabouts.
Jyotsna Clarkin
Ranch Hand

Joined: Jan 26, 2001
Posts: 158

or thereabouts.
Here's a diagram to clarify the stuff Dave said


HashSet SetPlus
| |
| |
legend: blue dash -> extends
red dash -> implements


You do not need an explicit cast

will work.
You also CANNOT instantiate an interface

I changed this to

These changes got your program working. Let me know if you can't fix it and I'll post the corrected code.

[This message has been edited by Jyotsna Clarkin (edited May 10, 2001).]
I agree. Here's the link:
subject: please help, class casting problem
It's not a secret anymore!