我使用的是返回List<String>
的opencsv
库的. readall方法。我认为List
是一个接口,因此不能实例化,所以它怎么能返回一个List<>
对象?
我认为,因为ArrayList<>
扩展了List
接口,我可以通过多态性做以下事情:
ArrayList<String[]> transactions = reader.readAll();
其中.readAll()
返回List<>
对象。但是,它不能工作,因为它期望List<>
而不是ArrayList<>
。
为什么多态性在这里不起作用,即为什么我不能将List<>
接口返回值分配给实现类ArrayList
?如何将接口实例化为方法返回值?
多态性的工作顺序与您所理解的相反,这意味着父类/接口的任何对象(在本例中是List
)都可以保存子类(或实现该接口的类)的值:
List a = new ArrayList(); //correct
ArrayList b = new List(); //incorrect
它怎么能返回一个List<>对象?
可以使用interface作为返回类型。阅读这个问题以获得澄清。
有趣的问题。它的答案并不简单。
- 我们不能创建接口的
instance
(接口不能被实例化),但we can make reference of it
引用其实现的对象类。
例句:
public List getData(){
...
...
ArrayList<String> sArrList = new ArrayList();
...
return sArrList;
}
所以,当你返回sArrList
时,它是一个数组列表,但是你的返回类型是列表。从第1点开始,列出一个数组列表的引用点,这是它的实现。
- 但相反的事情是不可能的。但是为什么呢?
看,ArrayList是List接口的一个可靠实现。List接口有一些可靠的实现,如ArrayList, LinkedList... .
因此,当我们尝试将List赋值给ArrayList时,Java编译器无法确定它实际上是哪个可靠的实现。它是数组列表还是链表?
因此,可以通过类型转换来克服这种情况。您确认java编译器,ok, don't worry, it is an arraylist. you can perform all arraylist operation here without further thinking :)