开发者

Type mismatch: cannot convert from ArrayList<Data> to MyCollection

开发者 https://www.devze.com 2022-12-26 17:14 出处:网络
I\'ve read similar questions here but I\'m still a little confused. MyCollection extends ArrayList<MyClass>

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 = som开发者_运维技巧ehandler.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


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.


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.


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.


you just need to cast the result

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

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


Check out page 4 of the generics tutorial.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消