I'm trying to create a method that returns an ArrayList of one of two types based on the class type passed in through the method.
public ArrayList<? extends Object> loadDataToList(Class<?> cls)
{
ArrayList<? extends Object> returnList = null;
File fileToLoad = null;
Object loadObject = null;
if (cls == CPassenger.class)
{
returnList = new ArrayList<CPassenger>();
fileToLoad = passengerFile;
loadObject = new CPassenger();
}
else if (cls == CFlightRecord.class)
{
returnList = new ArrayList<CFlightRecord>();
fileToLoad = flightRecordFile;
loadObject = new CFlightRecord();
}
else
{
return null;
}
boolean EOF = false;
try
{
ObjectInputStream in = new ObjectInputStream (new FileInputStream
(fileToLoad.getName()));
while (!EOF)
{
try
{
loadObject = cls.cast(in.readObject());
// Error is here.
returnList.add(loadObject);
} // try
catch (EOFException e)
{
EOF = true;
}
} // while (!EOF)
in.close ();
} // try
catch (Exception e)
{
e.printStackTrace (System.out);
}
return returnList;
}
The error that I'm getting when trying to add the loadObject the returnList is The method add(capture#6-of ? extends Object) in the type ArrayList<capture#6-of ? extends Object>
is not applicable for the arguments (Object).
Why does the add method not accept loadObject?