0

In the following code I get an error saying that collection cannot be converted to List. Why not? I thought when the method saveObject is called the part

List e = c;

equals

List e = ArrayList();

because c - although of type Collection - refers to ArrayList in the end

Code:

import java.util.*;
class Test {
int i;
Object prevObject;
public void saveObject(List e) {
    prevObject = e;
    i++;
}

public static void main (String[] args) {
    Test t = new Test();
    Collection c = new ArrayList();
    t.saveObject(c);
    }
}
Duke
  • 47
  • 1
  • 3
  • Think you should check this http://stackoverflow.com/questions/580160/how-convert-a-collection-to-list-in-java – Alberto Pérez Mar 13 '17 at 20:58
  • the referenced duplicate has really no relation with the encountered problem that is related to rules of the compiler to bind a call to a method. – davidxxx Mar 13 '17 at 21:01
  • Disagree that it's a dupe of that question. IMO the question is really more about the compiler and type system. @duke, the problem is that when you declare `Collection c`, you told the compiler to only care about `c` as a `Collection`; thus it essentially ignores the fact that in this particular line, `c` is an `ArrayList`. – Alejandro C. Mar 13 '17 at 21:02
  • A List is/extends a Collection and not the other way around. So when you try to pass a Collection to a method which requires a list the collection could be something else (for example a map, set or queue). – Christopher Rivera Mar 13 '17 at 21:04

1 Answers1

3

Parameter binding happens at compile time, not runtime. You are trying to pass a Collection (which could be anything implementing Collection) to a method that is expecting a List subclass. There are Collection classes that do not implement List so the compiler cannot guarantee that the cast is possible at runtime.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190