Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do classes that implement an interface not count as the same type as the interface in Java?

I have

out.load(output, transactions, columnHeaders, dataFormat);

Where load is defined as:

public boolean load(String outputfile, List<Transaction> transactions, List<String> columnHeaders, String dataFormat);

and

String output = "";
String dataFormat = "";
ArrayList<ARTransaction> transactions = new ArrayList<ARTransaction>();
List<String> columnHeaders = null;

where

ARTransaction implements Transaction

Why is there a problem on the type of transactions?

like image 978
Ritwik Bose Avatar asked Dec 03 '22 12:12

Ritwik Bose


2 Answers

public boolean load(String outputfile, List<? extends Transaction> transactions, List<String> columnHeaders, String dataFormat);

Or just declare transactions as a List<Transaction>.

Here's the common example of why you obviously can't do this:

List<String> list = new ArrayList<String>();
List<Object> objList = list; //if this were possible
objList.add(Integer.valueOf(5));
String val = list.get(0);  //ClassCastException here
System.out.println(val);
like image 57
Mark Peters Avatar answered Dec 06 '22 01:12

Mark Peters


It is having difficulties casting the contravariant type that is from ArrayList<ARTransaction> to List<Transaction>.

Try List<? extends Transaction> instead

like image 42
Matt Mitchell Avatar answered Dec 06 '22 02:12

Matt Mitchell