using parameterized ArrayList

Discussion in 'Java' started by ebby83, Mar 16, 2006.

  1. ebby83

    ebby83 Guest

    I am trying to read write <Event> objects to an ArrayList ... but when
    I try to convert the arraylist back to the object arrayit gives me a
    ClassCastException for the line

    return (Event[]) a.toArray();


    --------------------------------------
    BufferedReader ois = null;
    ArrayList<Event> a = new ArrayList<Event>();
    try {

    ois = new BufferedReader(new FileReader(this.calFile));

    Event e = null;
    String line;

    while ((line = ois.readLine()) != null) {
    e = new Event(line);
    a.add(e);
    }
    ois.close();
    } catch (FileNotFoundException e) {

    e.printStackTrace();
    } catch (IOException e) {

    e.printStackTrace();
    } catch (ParseException e) {

    e.printStackTrace();
    } catch (InvalidTimeRangeException e) {

    e.printStackTrace();
    }
    if (a.isEmpty())
    return null;
    return (Event[]) a.toArray();
     
    ebby83, Mar 16, 2006
    #1
    1. Advertisements

  2. try

    return (Event[]) a.toArray(new Event[0])

    for more info read documentation of toArray(T[])
     
    Marcin Wielgus, Mar 16, 2006
    #2
    1. Advertisements

  3. ebby83

    roy2000 Guest

    or simply
    return a.toArray(new Event[0])
     
    roy2000, Mar 16, 2006
    #3
  4. ebby83

    Piotr Kobzda Guest

    or better:
    return a.toArray(new Event[a.size()]);


    piotr
     
    Piotr Kobzda, Mar 16, 2006
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.