🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.api
Article #2067

Re: String[] casting of other arrays

#2067
From: Torsten Welches
Date: Mon, 04 Jun 2001 12:26
37 lines
2055 bytes
in addition to what Michael has said:

a)
you can't cast an array of Objects to an array of Strings, even if the array
of Objects contains only Strings
(that's what Michael meant I guess):

    Object[] source = { "One", "Two", "Three" };
    String[] copy = (String[])source; //ClassCastException

b)
what you *can* do is use System.arraycopy:

    Object[] source = { "One", "Two", "Three" };
    String[] copy = new String[source.length];
    System.arraycopy(source,0,copy,0,source.length);

c)
but you would get an ArrayStoreException if one of source's elements would
be no String instance:

    Object[] source = { "One", "Two", "Three", new Integer(4) };
    String[] copy = new String[source.length];
    System.arraycopy(source,0,copy,0,source.length); //ArrayStoreException

d)
you need to interate over all elements if you have an array of Objects that
might contain non-String instances - like in c) - or if you have an array of
Object subtypes:

    Object[] source = { "One", "Two", "Three", new Integer(4) };
    String[] copy = new String[source.length];
    for (int i = 0; i < source.length; i++) {
      copy[i] = source[i].toString();
    }

Torsten
Technical Details
Message-ID: <3b1b7e2d_2@dnews>
Path: arc1-ca.pugleaf.net!archiver1.google.com!newsfeed.google.com!sn-xit-02!supernews.com!nntp-relay.ihug.net!ihug.co.nz!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!dnews
References: <3b1a7545_1@dnews> <3b1b3609_1@dnews>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 1089d0,4cd3fd58a543ecae
X-Google-Attributes: gid1089d0,public
X-Google-ArrivalTime: 2001-06-04 05:45:26 PST
From: "Torsten Welches" <torsten.welches@who.cares.netcologne.de>
Newsgroups: borland.public.jbuilder.java.api
References: <3b1a7545_1@dnews> <3b1b3609_1@dnews>
Subject: Re: String[] casting of other arrays
Date: Mon, 4 Jun 2001 14:26:34 +0200
Lines: 40
X-Newsreader: Microsoft Outlook Express 4.72.3110.5
X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3110.3
NNTP-Posting-Host: 195.14.244.69
Message-ID: <3b1b7e2d_2@dnews>
X-Trace: dnews 991657517 195.14.244.69 (4 Jun 2001 05:25:17 -0700)
Path: arc1-ca.pugleaf.net!archiver1.google.com!newsfeed.google.com!sn-xit-02!supernews.com!nntp-relay.ihug.net!ihug.co.nz!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!dnews