Home arrow static arrow Java Programming [Archive] - ClassCastException
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - ClassCastException
This topic has 4 replies on 1 page.

Posts:210
Registered: 7/11/03
ClassCastException  
Jul 12, 2004 7:54 AM



 
Why does the line ( last one )

String[] parameters = ( String [ ] )out.toArray ( );

in the followinf code give me a ClassCastException ?

ArrayList out = new ArrayList( );

StringBuffer nameValue = new StringBuffer( );
nameValue.append ( "key1=value1" );
out.add ( nameValue.toString ( ) );
nameValue = null;
nameValue = new StringBuffer( );
nameValue.append ( "key2=value2" );
out.add ( nameValue.toString ( ) );
nameValue = null;
nameValue = new StringBuffer( );
nameValue.append ( "key3=value3" );
out.add ( nameValue.toString ( ) );

String[] parameters = ( String [ ] )out.toArray ( );

I know this can be solved by changing the last line to

String[] parameters = ( String [ ] )out.toArray ( new String[0] );

but I am curious why the first method doesn't work ?

Cheers
/Andreas

 

Posts:6,750
Registered: 1/25/04
Re: ClassCastException  
Jul 12, 2004 7:55 AM (reply 1 of 4)



 
Because an Object[] containing Strings isn't a String[].
 

Posts:18,384
Registered: 21.03.00
Re: ClassCastException  
Jul 12, 2004 7:57 AM (reply 2 of 4)



 
Hi,

It doesn't work because the ArrayList doesn't know that you want the array to be a String array. You can have any object in the list, so I would guess that the returned array is an Object array.

/Kaj
 

Posts:8,813
Registered: 10/4/00
Re: ClassCastException  
Jul 12, 2004 8:08 AM (reply 3 of 4)



 
Lifted from [url http://java.sun.com/developer/technicalArticles/Collections/Using/#customization]here[/url] and modified.
class StringArrayList extends java.util.ArrayList {    public StringArrayList() { super(); }    // other constructors ...    public boolean add(Object o) {      if (o instanceof String) return super.add(o);      else throw new UnsupportedOperationException();    }    // other add() and set() methods ...    public String[] toStringArray() {      int size = size();      String[] strings = new String[size];      for (int i=0; i<size; i++) strings[i] = (String)get(i);      return strings;    }}
 

Posts:1,649
Registered: 99-07-18
Re: ClassCastException  
Jul 12, 2004 10:54 AM (reply 4 of 4)



 
Instead of
 String[] parameters = ( String [ ] )out.toArray ( );


you could try:

Object[] o = out.toArray();String[] parameters=new String[o.length];System.arraycopy(o,0,parameters,0,parameters.length); 


..that is assuming that you know they are all Strings.
 
This topic has 4 replies on 1 page.