tags:

views:

59

answers:

6

I've read similar questions here but I'm still a little confused.

 MyCollection extends ArrayList<MyClass>

 MyClass implements Data

yet this gives me the "cannot convert from ArrayList to MyCollection"

 MyCollection mycollection = somehandler.getCollection();

where getCollection looks like this

 public ArrayList<Data> getCollection()

So my assumptions are obviously wrong. How can I make this work like I would like it to

A: 

you just need to cast the result

MyCollection mycollection = (MyCollection) somehandler.getCollection();

edit : or change the return type of getCollection() to a MyCollection

oedo
That will only work if `getCollection` actually returns an object of type `MyCollection`.
Joachim Sauer
+4  A: 

ArrayList does not extend MyCollection. It's the other way round.

There are several ways to fix this problem, depending on the functional requirement:

  1. You need to provide a MyCollection constructor which can take another Collection.
  2. If the actual type is MyCollection, then you need to cast ArrayList to MyCollection.
  3. If the actual type is MyCollection, then you need to change return type to MyCollection.

That said, what makes MyCollection so different that it apparently doesn't adhere the List's contract and you hence need to cast/convert it? This shouldn't happen, I would rethink the design/approach.

BalusC
+1  A: 

You can not assign to subtype from super type, but you can implement a Copy Constructor, then you could do the same thing like this:

MyCollection myCollection = new MyCollection(somehandler.getCollection());

Edit: the type of the parameter to the constructor could be for example List.

fish
+1  A: 

Well, imagine you have

class SecondCollection extends ArrayList<MyClass>

then what would ArrayList<MyClass> be cast to?

You need to either expect ArrayList or return MyCollection, or copy the contents of the ArrayList to a new instance of MyCollection, or explicitly cast to MyCollection. I don't recommend the last option.

Bozho
A: 

Check out page 4 of the generics tutorial.

John
A: 

ArrayList<Data> cannot be cast to MyCollection or even to ArrayList<MyClass>. See this post for a good explanation.

Drew Johnson