Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2005

Tip: Looking for answers? Try searching our database.

Array casting problem

Thread view: 
O.B. - 13 Dec 2005 21:36 GMT
Why does the cast in the following code snippet fail?

   private InternetAddress[] getAddressAsArray(String address) {
      List emails = new LinkedList();
      String[] addresses = address.split(",");
      for (int i = 0; i < addresses.length; i++) {
         String tempAddress = addresses[i].trim();
         if ( 0 < tempAddress.length()) {
            try {
               emails.add(new InternetAddress(tempAddress));
            } catch (AddressException e) {
               logger.error(e);
            }
         }
      }
      InternetAddress[] blah = null;;
      try {
         // Why is this causing a class cast exception?
         blah = (InternetAddress[])emails.toArray();
      } catch (RuntimeException e) {
         logger.error(e);
      }
      return blah;
   }
klynn47@comcast.net - 13 Dec 2005 21:52 GMT
You need to use the version of toArray that specifies the runtime type
of the array returned.

blah = (InternetAddress[])emails.toArray(new InternetAddress[0]);
Roedy Green - 13 Dec 2005 22:17 GMT
>blah = (InternetAddress[])emails.toArray(new InternetAddress[0]);

that needlessly creates an extra object and makes toArray go through
ugly means to create one the proper size.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Mike Schilling - 14 Dec 2005 05:44 GMT
>>blah = (InternetAddress[])emails.toArray(new InternetAddress[0]);
>
> that needlessly creates an extra object and makes toArray go through
> ugly means to create one the proper size.

Ugly?  It does the same calculation the caller would make to create one of
the proper size. i.e. call emails.size()..

I'd probably use a static InternetAddress[0] to avoid creating a new one
each time (the cost of a zero-length array being negligible), but I admit
I'm lazy when it comes to micro-optimizations.
Roedy Green - 14 Dec 2005 06:05 GMT
On Wed, 14 Dec 2005 05:44:29 GMT, "Mike Schilling"
<mscottschilling@hotmail.com> wrote, quoted or indirectly quoted
someone who said :

>Ugly?  It does the same calculation the caller would make to create one of
>the proper size. i.e. call emails.size()..

here is the code:

public <T> T[] toArray(T[] a) {
       if (a.length < size)
           a = (T[])java.lang.reflect.Array.newInstance(
                  a.getClass().getComponentType(), size);
       int i = 0;
       Object[] result = a;
       for (Entry<E> e = header.next; e != header; e = e.next)
           result[i++] = e.element;

       if (a.length > size)
           a[size] = null;

       return a;
   }

If you don't provide the array the proper size,  you use reflection to
create the new array, vs plain new to create it if you do provide it.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Mike Schilling - 14 Dec 2005 06:23 GMT
> On Wed, 14 Dec 2005 05:44:29 GMT, "Mike Schilling"
> <mscottschilling@hotmail.com> wrote, quoted or indirectly quoted
[quoted text clipped - 22 lines]
> If you don't provide the array the proper size,  you use reflection to
> create the new array, vs plain new to create it if you do provide it.

Thanks, I'd never looked at that code before, but now that you show it, it's
pretty obvious that that would be required.
Daniel Dyer - 13 Dec 2005 23:21 GMT
> You need to use the version of toArray that specifies the runtime type
> of the array returned.
>
> blah = (InternetAddress[])emails.toArray(new InternetAddress[0]);

The docs say:

"If the list fits in the specified array, it is returned therein.  
Otherwise, a new array is allocated with the runtime type of the specified  
array and the size of this list."

So, since you know the size of the collection, it's better to do it this  
way as you won't allocate two arrays:

    blah = (InternetAddress[])emails.toArray(new  
InternetAddress[emails.size()]);

Dan.

Signature

Daniel Dyer
http://www.dandyer.co.uk

Eric Sosman - 13 Dec 2005 22:00 GMT
O.B. wrote On 12/13/05 16:36,:
> Why does the cast in the following code snippet fail?
>
[quoted text clipped - 20 lines]
>        return blah;
>     }

   Because an array of Objects is not an array of
InternetAddresses, even if each individual element
of the Object array refers to an InternetAddress.
Use the other toArray() method of List:

    blah = (InternetAddress[])
       emails.toArray(new InternetAddress[0]);

Signature

Eric.Sosman@sun.com

Roedy Green - 13 Dec 2005 22:16 GMT
>   // Why is this causing a class cast exception?
>          blah = (InternetAddress[])emails.toArray();

Because you did not provide a template array to toArray
so you just got back an Object[]

See http://mindprod.com/jgloss/array.html
at the bottom
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.