CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2000
    Posts
    3

    problem casting Collection

    this causes a ClassCastException:

    ArrayList al = new ArrayList();
    al.add(new String("Adam"));
    al.add(new String("Bob"));
    al.add(new String("Carl"));

    String sl[] = (String [])al.toArray();

    does anyone know how to make this cast work?


  2. #2
    Join Date
    Sep 2000
    Location
    Melbourne --> Australia
    Posts
    68

    Re: problem casting Collection

    Hi there
    That method returns an Object array.
    The problem with this is that there is no
    way to cast an array of one type to an array
    of another type.
    You have to cast each individual element of the
    array to another type and place it in the
    appropriate array.
    One way to do this is :
    in the following loop, there is supposed to
    be an array index i after the str variable.


    ArrayList al = new ArrayList();
    al.add(new String("Adam"));
    al.add(new String("Bob"));
    al.add(new String("Carl"));
    String[] str = new String[al.size()];
    for(int i = 0; i < al.size(); i++){
    str[i] = (String)al.get(i);
    System.out.println(str[i]);
    }



    Phill.




Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured