4

I have the following code:

List<MassEditionObject> objects = getProjects();

where MassEditionObject is an interface that is implemented by the Project class.

getProjects() returns List<Project>, which seems like it should be fine because Project is a MassEditionObject.

However, Eclipse is giving me this error: Type mismatch: cannot convert from List<Project> to List<MassEditionObject>

I understand the general idea of interfaces and how to use them, I'm just not sure why this is invalid.

Thanks, and sorry if this question has been posted. I searched and found similar situations but none that answered this problem.

jlars62
  • 6,816
  • 7
  • 37
  • 57
  • Did you try to typecast the return value from getProjects() to List; some thing like this List variable = (List)(List>) collectionOfListA; – Priyatham51 Sep 19 '13 at 18:35

3 Answers3

6

If you want the proper generics version of this, it would be

List<? extends MassEditionObject> objects = getProjects();

You should read up on generics, it can be a bit complicated sometimes. Of course if you know that there will be a List<Project> returned, you could just that as the type. But if you had a class ProjectB that also implemented MassEditionObject they would both be acceptable.

List<? extends MassEditionObject> objects = getProjects();   // Return List<Project>
List<? extends MassEditionObject> objects2 = getProjectsB(); // Return List<ProjectB>
Kayaman
  • 70,361
  • 5
  • 75
  • 119
  • Ah, very nice! I did not know you could use the wildcard with interfaces. – jlars62 Sep 19 '13 at 18:41
  • Yea, the syntax is a bit confusing at first. – Kayaman Sep 19 '13 at 18:56
  • However note that using a wildcard as a return type is [not recommended](https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html), as it "forces the caller to deal with wildcards". So wildcards are something we don't really want to throw around willy-nilly. – Kayaman Jun 29 '20 at 10:28
0

You should do the contrary actually.

List<Project> object = getProjects() where getProjects() returns a List<MassEditionObject>.

A Project is a MassEditionObject. A MassEditionObject is not necessarily a Project.

Since my code above doesn't rly make sense in your case, you could just do

List<Project> object = getProjects() with the same getProjects you have now.

Or see @Kayaman's answer also.

Adrien Gorrell
  • 1,251
  • 3
  • 13
  • 27
0

change the return type to getObjects to

public List<? extends Project> getObjects();

and u can use it like this

List<Project> objs = getObjects();

List<MassEditionObject> mObjs = (List<MassEditionObject>)getObjects();
Eugen Halca
  • 1,765
  • 2
  • 12
  • 25