-1

I'm trying something that should be a simple case of polymorphism. I have a method that returns an object of type ArrayList and am trying to assign an object of type List to the return value of said method. Here's the code:

List<Object> inorder = parser.parseInorder();

Where I have a parser object to parse an incoming file, and the parseInorder() method returns an

ArrayList<Integer>.

Eclipse is giving me this error:

Type mismatch: cannot convert from ArrayList<Integer> to List<Object>
djar
  • 69
  • 1
  • 1
  • 9
  • 1
    And why can't you assign this to a `List` ? – Dawood ibn Kareem Dec 24 '15 at 06:40
  • How about: `List inorder = parser.parseInorder();` ? – Rahul Tripathi Dec 24 '15 at 06:42
  • The declaration really comes earlier in my code, as I may have to assign the List inorder to a value that returns List. – djar Dec 24 '15 at 06:43
  • So you want to be able to put Integers into the list, and pull Strings out? Sounds like something the compiler should stop you from doing. – Dawood ibn Kareem Dec 24 '15 at 06:44
  • 1
    Even though Integer is a sub-type of Object, ArrayList is not a sub-type of List. They are totally different types. That's why your compiler is complaining. – m.aibin Dec 24 '15 at 06:44
  • No @David Wallace. I have a List object that I'll either have to assign to a List object or an ArrayList object depending on events at runtime – djar Dec 24 '15 at 06:47
  • It sounds like you should rethink your design. These two things are not the same, so you can't really have a variable that can reference both. – Dawood ibn Kareem Dec 24 '15 at 06:48
  • Check out this article: https://dzone.com/articles/covariance-and-contravariance. It explains why you can't do what you just did. Essentially, since there's no type information at runtime, there's no way to ensure that there isn't heap pollution. Therefore to avoid this, the compiler will throw an error to prevent you from coercing an ArrayList of Integers to a List of Objects. – Quy Dec 24 '15 at 07:03
  • Maybe what you want is a `List>` instead of a `List`. That's the correct supertype of `List` and `ArrayList`. – Dawood ibn Kareem Dec 24 '15 at 07:22

1 Answers1

-1

Do this :

List<Integer> inorder = parser.parseInorder();
Rajnikant Patel
  • 561
  • 3
  • 19