在Java中将对象添加到通用ArrayList

时间:2015-03-03 13:31:58

标签: java list generics arraylist

我正在尝试创建一个方法,该方法根据通过该方法传入的类类型返回两种类型之一的ArrayList。

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;
}

我在尝试添加loadObject时遇到的错误返回列表是类型ArrayList<capture#6-of ? extends Object>中的方法add(capture#6-of?extends Object)不适用于参数(Object)。

为什么add方法不接受loadObject?

0 个答案:

没有答案