Cast Object Array to String Array.

When I try to cast an object array to string array an exception is thrown. How do I go about doing it?
Vector temp = new Vector();
Object[] array = temp.toArray();
String[] nonterms;                              
nonterms = (String[])array;
Thanks,
Ally

Try this
import java.util.Vector;
public class Test
     public static void main(String args[]) throws Exception
          Vector v = new Vector();
          v.add("a");
          v.add("b");
          v.add("c");
          Object[] terms = v.toArray();
          for(int i = 0; i < terms.length; i++)
               System.out.println((String)terms);
Raghu

Similar Messages

  • Array of String Arrays

    How do I make an array of String Arrays, not knowing how big the array will be
    or how big any of the arrays it contains will be at the time I create it?

    The size of an array is not dynamic, i.e. if you use an array, you must know its size at the time you create it.
    Use one of the collection classes (like java.util.Vector or one of the implementation classes of java.util.List).
    regards
    Jesper

  • How to convert an int array to string array?

    Hi,
    Can anyone please help me with this question?
    int number={4,6,45,3,2,77};
    I like to convert this into a list and sort
    List mylist = Arrays.asList(number);
    Collections.sort(mylist);
    But first I need to convert the int array to String array.
    Please advise. Thanks.

    If you want to convert your int array to a String array, you have no choice but doing a conversion element by element in a for loop.
    However, if the sort method doesn't behave as desired, you can use the one with 2 parameters, the second parameter being a comparator class.
    Check the javadoc for more information : http://java.sun.com/j2se/1.3/docs/api/java/util/Collections.html
    /Stephane

  • Read/Write 2d numeric array or string array into bin file

    Can anyone pls help me to resolve this problem
    Attachments:
    bin file.vi ‏9 KB

    You are still using the wrong format.
    Whatever you are doing has nothing to do with a binary file.
    You are still using way too much duplicate code.
    All you probably need is read/write from spreadsheet file, no need to reinvent the wheel.
    Your code will fail if the numbers contain decimal digits (since your array is DBL, it could! If your array only contains integers, you are using the wrong numeric representation).
    You string code will fail if the array elements contains tabs, for example.
    You still don't need a sequence structure.
    LabVIEW Champion . Do more with less code and in less time .

  • How to cast an array object to array of string

    * Can someone please tell me why SECTION 3 causes a cast
    * exception?
    * What I am really trying to do is put Strings into a vector and
    * return them as an array of String with a line like:
    *     return (String[])myVector.toArray();
    * How to do this?
    * Thank You!
    public class CastArrayTest
         public static void main(String args[]){
              //SECTION 1: This works
              String[] fruits = {"apple", "banana"};
              Object[] objs = (Object[])fruits;
              String[] foods = (String[])objs;
              for (int i = 0 ; i < foods.length ; i++){
                   System.out.println(foods);
              //SECTION 2: this works too
              Object anObj = new Object();
              String aString = "ok";
              anObj = aString;
              String anotherString = (String)anObj;
              System.out.println("word for single obj is " + anotherString);
              //SECTION 3: this causes cast exception at line
              // String[] strings = (String[])stuff
              Object[] stuff = new Object[2];
              String a = "try";
              String b = "this";
              stuff[0] = a;
              stuff[1] = b;
              String[] strings = (String[])stuff;
              for (int x = 0 ; x < strings.length ; x++){
                   String s = strings[x];
                   System.out.println("the string is " + strings[x]);

    I understand all replies so far, but from my
    understanding, objects are passed by reference No, they're not. Rather, object references are passed by value.
    Object obj = new Object();
    String a = "pass me by reference";
    Object anotherObj = (Object)a; // this explicit cast is not necessary
    String anotherString = (String)anotherObj; // this cast works because the object in question is a String
    There's no passing in that code, so I'm not sure where that even came from. However, that works because it's all legal casting.
    works as I think it should, and does, and futhermore
    String[] cast to Obj[] cast to String[] works also...Because the object you're casting actually is a String[].
    so why not if Obj[] to String[] Because String[] is not a subclass of Object[]. That's just how the language is specified.
    futhermore if they are
    all string...Again, this has no bearing on the type of the array object.
    I saw hot to cast array to String[] and wondered if
    this is real cast or calls the toString method...It's a real cast.
    but most importantly, does this mean if I have a
    vector of Strings and want to get them as an array of
    strings, I have to loop through the Obj[] (or vector)
    and cast each to (String)...just to get them as an
    array of String[]....No, zparticle's code can do that.

  • H:dataTable value as array of Strings vs array of objects

    I'm trying to use a h:dataTable with an h:inputText as one of the columns. If my bean returns an array of Strings, then the h:dataTable can't update them. (I added a submit button that just updates the fields and returns to the current page.) If I use an array of objects, in this case a simple wrapper class, it works. Why is this?
    This won't work:
    public class EmailBean {
        private String[] m_emails;
        public String[] getEmails() {
            return m_emails;
        public void setEmails(String[] emails) {
            m_emails = emails;
    }But this will:
    public class EmailBean {
        private Email[] m_emails;
        public EmailBean() {
            m_emails = new Email[] {
                    new Email("[email protected]"),
                    new Email("[email protected]"),
                    new Email("[email protected]")
        public Email[] getEmails() {
            return m_emails;
        public void setEmails(Email[] emails) {
            m_emails = emails;
    }

    public class Email {
        private String email;
        public Email(String email) {
            this.email = email;
        public String getEmail() {
            return email;
        public void setEmail(String email) {
            this.email = email;
    }For the one that uses the Email class, I use this:
    <h:dataTable value="#{emailTestBean.emails}"
                                  var="email">
         <h:column>
              <f:facet name="header">
                   <h:outputText value="Email Address" />
              </f:facet>
              <h:inputText value="#{email.email}" />
         </h:column>
         <f:facet name="footer">
              <h:commandButton value="Submit" />
         </f:facet>
    </h:dataTable>Otherwise I don't need the extra ".email":
    <h:dataTable value="#{emailTestBean.emails}"
                                  var="email">
         <h:column>
              <f:facet name="header">
                   <h:outputText value="Email Address" />
              </f:facet>
              <h:inputText value="#{email}" />
         </h:column>
         <f:facet name="footer">
              <h:commandButton value="Submit" />
         </f:facet>
    </h:dataTable>

  • Using an array of strings to name an object

    Hey everyone
    I have an array of strings that are supposed to be the names of each panel in a grid, but I dont know how to use the string values to name the panels. From searching the forums almost everything refered to using a Map to do this, but I still can't grasp how to use one. Can someone help me with this?
    import java.awt.*;
    import javax.swing.border.*;
    import javax.swing.*;
    public class test
        public test()
        public JPanel grid()
             JPanel mainPanel = new JPanel(new GridLayout(10, 10));
             String [] names = new String[100];
             Border innerBorder = BorderFactory.createLineBorder(Color.black, 1);
              for (int i = 0; i < 100; i++)
                   names[i] = "Panel" + i;
              for (int r = 0; r < 100; r++)
                   String varName = names[r];
                   JPanel /*I would like the JPanel to be named what the string varName is*/justSoItCompiles = new JPanel(new GridLayout(2,1));
                   /*The JPanel above*/justSoItCompiles.setBorder(innerBorder);
                   mainPanel.add(justSoItCompiles);
              return mainPanel;
    }Thanks in advance

    You just make a Map as:
    Map<String, JPanel> panelMap = new HashMap<String, JPanel>();then add a panel as
    panelMap.add("Panel1", new JPanel());then you can do whatever with it by saying
    panelMap.get("Panel1").add(something);Make sense?

  • Converting vector to string array

    How can I convert values in a vector into a string array?
    Vector formsVector = new Vector();
    while (rs.next())
    {formsVector.add(rs.getString("forms"));}
    String forms[] = (String[])formsVector.toArray();
    I tried the above line but it did not work. Any input please?
    Thanks

    .... What is the difference between the two as
    according to online help, both are same.
    String forms[] = (String [])formsVector.toArray();
    String forms[] = (String [])formsVector.toArray( new
    String[0] );The difference lies in the type of the object returned from toArray. The first form you list, formsVector.toArray(), always returns an Object[]. In your example, you'll get a ClassCastException at runtime when you cast to String[].
    The second form will try to use the array you pass in. If it's not big enough, it'll create a new one of the same type as that array. This is what's happening when passing a zero-length array into toArray.
    My personal preference is to save an extra instantiation and build the array to the proper size to begin with:String forms[] = (String [])formsVector.toArray( new String[formsVector.size()] );

  • SIMPLE QUESTION! converting an Enumeration to a String array;

    Enumeration e=request.getParameterNames();
    i have an enumeration that contains some String objects
    how can i convert it to a String array?
    thanks a lot.

    String str = null;
    List list = new ArrayList();
    while(e.hasMoreElements()) {
         str = (String)e.nextElement();
         list.add(str);
    String[] strArray = (String[]) list.toArray();
    Disclaimer: Code not tested; use at your own
    risk ;)Taht piece of code will probably throw class cast exception at the line:
    String[] strArray = (String[]) list.toArray();The array returned is an object array. You should use:
    String[] strArray = (String[]) list.toArray(new String[list.size()]);That methods returns an array of the same type as the argument.
    /Kaj

  • Problem in converting vector to array of strings

    hi
    i am having a vector which in turn contains hashtable as elements
    Vector v=new Vector()
    Hashtable ht=new Hashtable();
    v.add(ht.add("key1",value1))
    v.add(ht.add("key2",value2))
    v.add(ht.add("key3",value3))
    v.add(ht.add("key4",value4))now i am trying to conver this vector in to a array of string like
    String[] str=(String[])v.toArray(new String[v.size()]);but i am getting java.lang.ArrayStoreExceptioncan anybody help me plz
    Thanks

    Hi,
    The api for public Object[] toArray(Object[] a) says
    Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.
    ArrayStoreException will be thrown if the runtime type of a is not a supertype of the runtime type of every element in this Vector.
    The runtime type of the elements of the vector is Hashtable.
    Because String is not a supertype of Hashtable the ArrayStoreException is thrown.

  • Large string array in 6.1 is extremely slow

    Good day all,
    While this is in to tech support at NI, I wanted to see if anyone else has encountered it.
    I am upgrading from 6.0.2 to 6.1. Several large (2500 rows by 250 columns or larger) string arrays are used as inputs into subvi's. Under 6.0.2, these functions run in tenths of seconds, while under the converted 6.1 vi's they run in 20 seconds or more!
    Tracing back using probes, the problem is occurring at the point of the input. It is appears that the array is taking many seconds to copy from the input to the wire on the diagram.
    Array controls generated in 6.1 (not converted from 6.0.2) seem to function just fine. Using a save with options... to convert back to 6.0.2, the vi's again function in tenths of
    seconds.
    Anyone have any ideas?
    Thanks!

    I hear what you're saying about legacy code...
    Something you might want to be looking at for the future is migrating to a structure where the data is stored in a 1D array, where each element is a cluster contain the data that's now in a single row. This would be the most straight-forward change, but could make getting at the data tricky, depending on how you need to be able to search it.
    Alternately, you could have a cluster containing arrays of each of the row values.In this structure element 0 of all the arrays is the first "row", element 1 of the arrays is the second "row" and so on. This structure at first blush looks more complicated, but it's really not, plus it would allow you to use any value (or combination of
    values) to search for a specific row without a lot of parsing.
    If the data that is in the example VIs you posted is typical, either of these changes would be advantagous because it looks like there is a lot of reptative data that might be able to be encoded in an enum. Plus storing numbers as numbers often reduces the memory required and produces a predictable memory footprint (an I32 will always take-up 4 bytes per value regardless of how large of small the number is). My sense is that the variability of the string size is what's killing you.
    One thing that would make this sort of dramatic change somewhat easier is that because you are changing the basic datatype of the interface, you aren't going to have to worry about finding all the places the change will effect--the wires will be broken.
    If you ever decide to take this on, give a hollar.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Newbie trying to sort 2D string array

    Dear all,
    After read some book chapters, web sites including this, I still don't get the point.
    If I have a file like,
    1 aaa 213 0.9
    3 cbb 514 0.1
    2 abc 219 1.3
    9 bbc 417 10.4
    8 dee 887 2.1
    9 bba 111 7.1
    and I load into memory as a String[][]
    here comes the problem, I sort by column 1 (aaa,...,bba) using an adaptation of the Quicksort algorithm for 2D arrays
    * Sort for a 2D String array
    * @param a an String 2D array
    * @param column column to be sort
    public static void sort(String[][] a, int column) throws Exception {
    QuickSort(a, 0, a.length - 1, column);
    /** Sort elements using QuickSort algorithm
    static void QuickSort(String[][] a, int lo0, int hi0, int column) throws Exception {
    int lo = lo0;
    int hi = hi0;
    int mid;
    String mitad;
    if ( hi0 > lo0) {
    /* Arbitrarily establishing partition element as the midpoint of
    * the array.
    mid = ( lo0 + hi0 ) / 2 ;
    mitad = a[mid][column];
    // loop through the array until indices cross
    while( lo <= hi ) {
    /* find the first element that is greater than or equal to
    * the partition element starting from the left Index.
    while( ( lo < hi0 ) && ( a[lo][column].compareTo(mitad)<0))
    ++lo;
    /* find an element that is smaller than or equal to
    * the partition element starting from the right Index.
    while( ( hi > lo0 ) && ( a[hi][column].compareTo(mitad)>0))
    --hi;
    // if the indexes have not crossed, swap
    if( lo <= hi )
    swap(a, lo, hi);
    ++lo;
    --hi;
    /* If the right index has not reached the left side of array
    * must now sort the left partition.
    if( lo0 < hi )
    QuickSort( a, lo0, hi, column );
    /* If the left index has not reached the right side of array
    * must now sort the right partition.
    if( lo < hi0 )
    QuickSort( a, lo, hi0, column );
    * swap 2D String column
    private static void swap(String[][] array, int k1, int k2){
    String[] temp = array[k1];
    array[k1] = array[k2];
    array[k2] = temp;
    ----- end of the code --------
    if I call this from the main module like this
    import MyUtil.*;
    public class kaka
    public static void main(String[] args) throws Exception
    String[][]a = MyUtil.fileToArray("array.txt");
    MyMatrix.printf(a);
    System.out.println("");
    MyMatrix.sort(a,1);
    MyMatrix.printf(a);
    System.out.println("");
    MyMatrix.sort(a,3);
    MyMatrix.printf(a);
    for the first sorting I get
    1 aaa 213 0.9
    2 abc 219 1.3
    9 bba 111 7.1
    9 bbc 417 10.4
    3 cbb 514 0.1
    8 dee 887 2.1
    (lexicographic)
    but for the second one (column 3) I get
    3 cbb 514 0.1
    1 aaa 213 0.9
    2 abc 219 1.3
    9 bbc 417 10.4
    8 dee 887 2.1
    9 bba 111 7.1
    this is not the order I want to apply to this sorting, I would like to create my own one. but or I can't or I don't know how to use a comparator on this case.
    I don't know if I am rediscovering the wheel with my (Sort String[][], but I think that has be an easy way to sort arrays of arrays better than this one.
    I've been trying to understand the Question of the week 106 (http://developer.java.sun.com/developer/qow/archive/106/) that sounds similar, and perfect for my case. But I don't know how to pass my arrays values to the class Fred().
    Any help will be deeply appreciated
    Thanks for your help and your attention
    Pedro

    public class StringArrayComparator implements Comparator {
      int sortColumn = 0;
      public int setSortColumn(c) { sortColumn = c; }
      public int compareTo(Object o1, Object o2) {
        if (o1 == null && o2 == null)
          return 0;
        if (o1 == null)
          return -1;
        if (o2 == null)
          return 1;
        String[] s1 = (String[])o1;
        String[] s2 = (String[])o2;
        // I assume the elements at position sortColumn is
        // not null nor out of bounds.
        return s1[sortColumn].compareTo(s2[sortColumn]);
    // Then you can use this to sort the 2D array:
    Comparator comparator = new StringArrayComparator();
    comparator.setSortColumn(0); // sort by first column
    String[][] array = ...
    Arrays.sort(array, comparator);I haven't tested the code, so there might be some compiler errors, or an error in the logic.

  • "Using a CIN to Create an Array of Strings in LabVIEW" example crashes LV on Linux

    Tried to utilize this NI example: "Using a CIN to Create an Array of Strings in LabVIEW" (http://sine.ni.com/apps/we/niepd_web_display.display_epd4?p_guid=B4B282BE7EF907C8E034080020E74861&p_node=&p_source=External)
    Compiles OK with the makefile made by the LV's lvmkmf utility. Nevertheless when I try to run the VI (with the code loaded into the CIN, of course), LabVIEW 7.1.1 on a SUSE 9.3 Linux machine crashes:
    LabVIEW caught fatal signal
    7.1.1 - Received SIGSEGV
    Reason: address not mapped to object
    Attempt to reference address: 0x0
    Segmentation fault
    Any ideas? Did anybody try this on a Windows machine?

    H View Labs wrote:
    Tried to utilize this NI example: "Using a CIN to Create an Array of Strings in LabVIEW" (http://sine.ni.com/apps/we/niepd_web_display.display_epd4?p_guid=B4B282BE7EF907C8E034080020E74861&p_node=&p_source=External)
    Compiles OK with the makefile made by the LV's lvmkmf utility. Nevertheless when I try to run the VI (with the code loaded into the CIN, of course), LabVIEW 7.1.1 on a SUSE 9.3 Linux machine crashes:
    LabVIEW caught fatal signal
    7.1.1 - Received SIGSEGV
    Reason: address not mapped to object
    Attempt to reference address: 0x0
    Segmentation fault
    Any ideas? Did anybody try this on a Windows machine?
    This code is badly broken. In addition to resizing the actual handle to hold the number of string handles you also would need to create the string handles itself before attempting to write into them. NumericArrayResize is the fucntion to use as it will either resize an existing handle (if any) or create a new one if the value is uninitialized (NULL).
    /* resize strarr to hold handles to NUMSTRINGS strings */
    err = SetCINArraySize((UHandle)strarr, 0, NUMSTRINGS);
    if (err)
    goto out;
    /* perform this loop once for each element */
    /* of array of strings being created */
    for (i = 0; i < NUMSTRINGS;) {
    LStrHandle handle = (*strarr)->arg1[i];
    /* determine length of string that will be element of strarr */
    strsize = StrLen(str[i]);
    err = NumericArrayResize(uB, 1, &handle, strsize);
    if (err)
    goto out;
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    /* moves strsize bytes from the address pointed to */
    /* by str[i] to the address pointed to by the data pointer in the handle */
    MoveBlock(str[i], LStrBuf(*handle), strsize);
    /* manually set size of string pointed to by *strarr */
    (*((*strarr)->arg1[i]))->cnt = strsize;
    /* manually set dimSize of strarr */
    (*strarr)->dimSize = ++i;
    return noErr;
    out:
    return err;
    Rolf KalbermatterMessage Edited by rolfk on 06-30-2005 03:15 AM
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • How to retrieve string array using Session?

    Hi, I am having some problem retrieving string arrays through session.
    String personalData[] = new String[17];
    personalData = (String [])session.getValue("PersonalData");
    The coding above isn't working. Advise pls.. Thanks

    The getValue() method is deprecated - you should probably be using getAttribute.
    What about this code isn't working? Looks ok to me, as long as the "PersonalData" object in the session is a String[] it should work.
    Cheers,
    evnafets

  • How  to Pass String array from Java to PL/SQL  and this use in CURSOR

    hi,
    I cant understand how to pass Array String as Input Parameter to the Procedure and this array use in Cursor for where condition like where SYMPTOM in( ** Array String **).
    This array containing like (SYMPTOM ) to be returned from the java to the
    pl/sql (I am not querying the database to retrieve the information).
    I cannot find an example on this. I will give the PL/SQL block
    create or replace procedure DISEASE_DTL<*** String Array ***> as
    v_SYMPTOM number(5);
    CURSOR C1 is
    select distinct a.DISEASE_NAME from SYMPTOM_DISEASE_RD a
    where ltrim(rtrim(a.SYMPTOM)) in ('Fever','COUGH','Headache','Rash') ------- ***** Here use this array element(like n1,n2,n3,n4,n5..) ******
    group by a.DISEASE_NAME having count(a.DISEASE_NAME) > 3 ----------- ***** 3 is no of array element - 1 (i.e( n - 1))*****
    order by a.DISEASE_NAME ;
    begin
    for C1rec IN C1 loop
    select count(distinct(A.SYMPTOM)) into v_SYMPTOM from SYMPTOM_DISEASE_RD a where A.DISEASE_NAME = C1rec.DISEASE_NAME;
    insert into TEMP_DISEASE_DTLS_SYMPTOM_RD
    values (SL_ID_SEQ.nextval,
    C1rec.DISEASE_NAME,
    (4/v_SYMPTOM), --------**** 4 is no of array element (n)************
    (1-(4/v_SYMPTOM)));
    end loop;
    commit;
    end DISEASE_DTL;
    Please give the proper solution and step ..
    Thanking you,
    Asish

    I've haven't properly read through your code but here's an artificial example based on a sql collection of object types - you don't need that, you just need a type table of varchar2 rather than a type table of oracle object type:
    http://orastory.wordpress.com/2007/05/01/upscaling-your-jdbc-app/

Maybe you are looking for