Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

please help, class casting problem

 
Josh Wetzel
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!
FILE 1
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);
}
}
FILE 2
import java.util.*;
interface SetPlus extends Set {
SetPlus union(SetPlus s2);
}
FILE 3
import java.util.*;
public class HashSetPlus extends HashSet implements SetPlus {
public SetPlus union(SetPlus s2) {
SetPlus z = new SetPlus(s2);
z.addAll(this);
z.addAll(s2);
return z;
}
}
}
 
Andy Ceponis
Ranch Hand
Posts: 782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Dave.
 
Jyotsna Clarkin
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

or thereabouts.
Dave.
[/b]
</BLOCKQUOTE>
Here's a diagram to clarify the stuff Dave said
<html>
<head>
<body>
<pre>

Set

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


</body>
</head>
</html>

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.
regards,
Jyotsna

[This message has been edited by Jyotsna Clarkin (edited May 10, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic