Reputation: 73
This is a Java Assignment question, possibly concerning sub-typing and generics. I have a class that extends ArrayList
called Rows
public class Rows extends ArrayList<List<Thing>> implements List<List<Thing>>{}
I need to return it in another class which has a method that returns a List<List<Thing>>
, thus I need to do this in order to get the desired return type:
private List<List<Thing>> list;
public List<List<Thing>> rows() {
Rows r = (Rows) list;// But this cast does not work at runtime
return (List<List<Thing>>) r;
}
The error Eclipse returns is java.lang.ClassCastException: java.util.ArrayList
cannot be cast to package.Rows. I am quite confused as my Rows class extends ArrayList
and I thought that it should be able to be cast to it.
Upvotes: 2
Views: 405
Reputation: 29223
Rows extends ArrayList<List<Thing>>
The above definition says that Rows
is a subclass of ArrayList<List<Thing>>
(which means it's a specialized version), not that Rows
is the same thing as an ArrayList<List<Thing>>
.
This means that a Rows
is a kind of ArrayList<List<Thing>>
(so upcasting works) but an ArrayList<List<Thing>>
is not necessarily a Rows
(so downcasting doesn't work).
If you have an object that you've created as a new ArrayList<List<Thing>>
, then this is its type and you can't downcast it further. If you want to be able to use it as a Rows
, you simply need to create it it as a new Rows
.
(By the way, plural is unconventional for class names.)
Upvotes: 1