Reputation: 3
My code fails with a ClassCastException
while running. I've tried to debug but in vain. I have declared a Class Subject with fields and am trying to load objects of that class into a list. Below is the code. It fails at the line: List items = (List)(it.next())
. Adding ?
for generics does not help. I guess the object is cast, though there are no generics mentioned in the List
declaration. Is there a basic concept that I'm missing here?
In the below method, I'm trying to encode the data into an xml file.
private void encodeSection(PrintStream output, Indenter indenter,
String name, List list) {
String indent = indenter.makeString();
output.println(indent + "<" + name + "s>");
indenter.in();
String indentNext = indenter.makeString();
if (list == null) {
// the match is any
output.println(indentNext + "<Any" + name + "/>");
} else {
String nextIndent = indenter.makeString();
Iterator it = list.iterator();
indenter.in();
while (it.hasNext()) {
List items = (List)(it.next());//-------------> Error occurs
output.println(indentNext + "<" + name + ">");
Iterator matchIterator = items.iterator();
while (matchIterator.hasNext()) {
TargetMatch tm = (TargetMatch)(matchIterator.next());
tm.encode(output, indenter);
}
output.println(indentNext + "</" + name + ">");
}
indenter.out();
}
indenter.out();
output.println(indent + "</" + name + "s>");
}
}
Stack Trace:
Exception in thread "main" java.lang.ClassCastException: SubjectID_V cannot be cast to java.util.List
at Target_V.encodeSection(Target_V.java:71)
at Target_V.encode(Target_V.java:41)
at com.sun.xacml.AbstractPolicy.encodeCommonElements(Unknown Source)
at com.sun.xacml.PolicySet.encode(Unknown Source)
at PolicyFactory_V.main(PolicyFactory_V.java:56)
Upvotes: 0
Views: 1356
Reputation: 393791
List items = (List)(it.next())
will only work if the List
you are iterating over contains just elements of type List
(i.e. instances of classes implementing the List
interface).
Based on the error you got, you are trying to cast an instance of type SubjectID_V
to a List
. You should look at the code that initializes that list. Your error might be there.
Using generic Lists may have helped you to avoid this exception, since it would have prevented the code from passing compilation in the first place.
Upvotes: 2