Vector to String Array

Hello all...
How can i convert a vector to a string array?

If it's inserted into the vector as a String, then the toArray() method is exactly what you want. Otherwise, a simple for loop doing a "array[i] = thing.toString()" bit ought to do nicely.

Similar Messages

  • 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()] );

  • Vector to String[] Conversion

    Hi All,
    I am trying to convert Vector to String Array. the problem is when I tried to print the String Array out side the loop I am getting only last value.
    I want to pass String Array to another function.
    How to do that?
    Find the code below:-
    Vector vec=new Vector()
    vec.add("abc\\aa.doc");
    vec.add("abc\\ccc.doc");
    vec.add("abc\\bb.doc");                  
    String [] arr=new String[vec.size()];
          for(int i=0;i<=vec.size();i++){
                       arr=vec.get(i).toString();
    System.out.println( "ARRAY" + arr);
    Current Output
    Output :- ARRAY abc\\bb.doc
    Desired Output
    ARRAY abc\\aa.doc,,abc\ccc.doc,abc\\bb.doc
    Thanks.

    OK,
    My vector contains Objects...
    I tried to use the following code
    String[] attachments = new String[setOfHandle.size()];
    for (int i = 0; i < setOfHandle.size(); i++) {
           attachments[i] = String.valueOf(setOfHandle.get(i));
         // if attachments exists, add them
         if ( attachments != null ) {
                           addAtta( maild, attachments );
                           checkPoint = false;
    }In the above code setOfHandle is a vector contains objects.. I need to convert it to String[] and pass it to addAtta.
    While doing this I am getting an error
    java.lang.ArrayIndexOutOfBoundsException: 1

  • String[] array = (String[])vector.toArray();

    Why does the last line cause a ClassCastException?:
    Vector vector = new Vector();
    vector.add("One");
    vector.add("Two");
    vector.add("Three");
    vector.add("Four");
    vector.add("Five");
    String[] array = (String[])vector.toArray();
    Thanks
    [email protected]

    Because toArray () creates an Object array. You need the toArray(Object[]):String[] array = (String[]) vector.toArray (new String[vector.size ()]);Kind regards,
      Levi

  • 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

  • Vectors to String

    hi i have a Vector which contains string elemets
    now i would like to create a string array but when i cast it
    like (String []) vector.toArray();
    dose not work comes out with all of the data being @and some numbers
    not that new to java but cant seem to get it to work.
    there are other ways to but none seem to work can you please tell me the best way???
    thanks

    when you do just a vector.toArray() it will return a Object[].
    Try:
    (String[]) vector.toArray(new String[vector.length()]);

  • 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

  • Get String array from Resultset

    In Tomcat 6.0.20 I am attempting to create an Oracle 9i resultset that outputs as a String array and need help creating the method.
    The CityData getCityList() method will be called in the CityServlet:
    CityServlet: String [] citys = cityData.getCityList();
    I started my below attempt but not sure how to handle the List/array part:
    CityData class: public ArrayList<String> getCityList() {     try {           .....           List<String> citys = new ArrayList<String>();           while(rs.next())           {               citys.add(rs.getString("city"));           }       }     return citys; }

    Hi!
    Try this:
    public City[] getCitys() throws Exception
        String sql = "SELECT * FROM citys ORDER BY name ASC";
        Vector v = new Vector();       
        ResultSet rs = null;
        java.sql.Statement stmt = null;
        try
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            while( rs.next() )
                City city = new City(rs);
                v.add(city);
        catch (Exception e) { throw e; }
        finally
            try
                if (stmt != null) stmt.close();
            catch (Exception e) { throw e; }
        City[] citys = new City[v.size()];
        for (int i = 0; i < citys.length; i++)
            citys[i] = (City)v.get(i);
        return citys;       
    }Edited by: Bejglee on Mar 3, 2010 3:59 AM

  • How to conver vector to Int array

    Hi
    I know toArray method can be used to convert vector to an array but what if I want to convert it to an int array?
    Vector v = new Vector();
    int r [] = new int [1];
    v.add(2);
    r = v.toArray()//gives errorHow can I cast it to return int Array rather than object array?

    Vector v = new Vector(10);
    for(int i = 0; i < 10; i++) {
        v.add(i);
    int r[] = new int[v.size()];
    for(int i = 0; i < r.length; i++) {
        String value = v.elementAt(i).toString();
        r[i] = Integer.valueOf( value ).intValue();
        System.out.println(r);

  • How to convert String array into int.

    void getSoldSms(Vector vecSoldSms)
         String str[]=new String[vecSoldSms.size()];
         String words[]=new String[str.length]; // String array
              for(int i=0;i< vecSoldSms.size();i++)
                   str=(String)vecSoldSms.get(i);
              }               //End for
              for(int i=0;i<str.length;i++)
              words = str[i].split("\\|\\|");
              System.out.println();
              for(int j=0;j<1;j++)     
              int count[str.length]=Integer.parseInt(words[i]);
              System.out.print(count[j]*advance_count);
              } // end inner for loop
              }          //End for
         }          //End function getSoldSms
    how do i convert words which is a string array into int type. i kno string can be converted into int using interger.parseint. but wat abt string arrays??? plz help me out with the above code.

    i did tht its still giving the same errorFor Heaven's sake, what about taking a second to try to understand the code you're copying first? If you really can't fix the error yourself, you have a more serious problem than just convertingStrings to ints.
    And if you want { "1", "2", "3" } to be 123:
    StringBuffer b = new StringBuffer();
    for (int i = 0; i < array.length; i++) {
      b.append(array);
    int result = Integer.parseIn(b.toString());

  • Converting a vector to an array

    hello :-)
    i am converting my vector into an array with this syntax:
    String[] lmname = (String[])name.toArray();
    and try to print my array with
    for(int i=0; i<lmname.size; i++)     
    System.out.println(lmname);
    unfortunately, i get this error:
    java.lang.ClassCastException
    what did i do wrong?

    -- you cannot do that...
    - if you still want to convert Vector into String[] then you can do this:
                 Vector v=new Vector();
               v.add("1");
               v.add("2");
               v.add("3");
               v.add("4");
               String strVector[]=new String[v.size()];
               for (int i = 0; i<v.size(); i++)
                       strVector=new String((String)v.get(i));
         for (int i = 0; i<strVector.length; i++)
         System.out.println (strVector[i]);
    ... By the way, you can use List instead of Vector,,,

  • Vector.add(String[]) error!

    Hi all,
    Please look at the code:
    String[] aRow = new String[7];
    Enumeration enum = home.findByParentKey(pk);
    while (enum.hasMoreElements()) {
    co = (CompanyOrgan) enum.nextElement();
    com = co.getData();
    aRow[0] = String.valueOf(com.getAbbrName());
    aRow[1] = String.valueOf(com.getOrganId());
    aRow[2] = String.valueOf(com.getGrade));
    aRow[3] = String.valueOf(com.getGradeName());
    aRow[4] = String.valueOfcom.getAddress));
    aRow[5] = String.valueOf(com.getTelephone());
    aRow[6] = String.valueOf(com.getFax());
    vect.add(aRow);
    there are 7 different aRow[](String arrays ) added to the vector, but when I retrieve the data from the vector using:
    (String[])vect1.elementAt(i);
    All the 7 Arrays are same.
    Why ?
    Thanks in advance!
    Leo

    have not tested but it should be some thing li,ke this
    while(e.hasMoreElememnts(){
    String ob[]=e.nextelement();
    for(inc=0;inc<ob.length;inc++){
    System.out.println(ob[inc]);
    }

  • Problems with string array, please help!

    I have a String array floor[][], it has 20 rows and columns
    After I do some statement to modify it, I print this array
    out in JTextArea, why the output be like this?
    null* null....
    null null...
    null null...
    How to correct it?

    a turtle graphics applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TG extends JApplet implements ActionListener {
      private int x, y;
      private int pendown, command, movement;
      String direction, output, temp;
      JLabel l1;
      JTextField tf1;
      JTextArea ta1;
      String floor[][] = new String[20][20];;
      public void init()
        x = 0;
        y = 0;
        pendown = 0;
        direction = "r";
        Container c = getContentPane();
        c.setLayout( new FlowLayout() );
           l1 = new JLabel( "Please type a command:" );
           c.add( l1 );
           tf1 = new JTextField(20);
           tf1.addActionListener( this );
           c.add( tf1 );
           ta1 = new JTextArea(20,20);
           ta1.setEditable( false );
           c.add( ta1 );
    public void actionPerformed( ActionEvent e )
           temp = tf1.getText();
           if( temp.length() > 1)
           command = Integer.parseInt(temp.substring(0,1));
           movement = Integer.parseInt(temp.substring(2,temp.length()));
           else
           command = Integer.parseInt(temp);
           switch(command)
                case 1:
                pendown=0;
                break;
                case 2:
                pendown=1;
                break;
                case 3:
                direct("r");
                break;
                case 4:
                direct("l");
                break;
                case 5:
               move(movement);           
                break;
                case 6:
                print();
                break;                                     
      public void direct(String s)
           if(direction == "r" && s =="r")
              direction = "d";
           else if(direction == "r" && s =="l")
              direction = "u";
           else if(direction == "l" && s =="r")
              direction = "u";
           else if(direction == "l" && s =="l")
              direction = "d";
           else if(direction == "u" && s =="r")
              direction = "r";
           else if(direction == "u" && s =="l")
              direction = "l";
           else if(direction == "d" && s =="r")
              direction = "l";
           else if(direction == "d" && s =="l")
              direction = "r";
      public void move(int movement)
           if(pendown == 1)
                if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "*";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "*";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "*";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "*";
            else if(pendown == 0)
                 if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "-";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "-";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "-";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "-";
          public void print()
         for(int row=0;row<20;row++)
           for( int column=0;column<20;column++)
                output += floor[row][column];
                if(column == 19)
                 output+="\n";
            ta1.setText(output);
    }

  • Problems with string arrays

    Previous task was:
    Write a class "QuestionAnalyser" which has a method "turnAnswerToScore". This method takes a String parameter and returns an int. The int returned depends upon the parameter:
    parameter score
    "A" 1
    "B" 2
    "C" 3
    other 0
    Alright, here's the recent task:
    Write another method "turnAnswersToScore". This method takes an array of Strings as a parameter, works out the numerical score for each array entry, and adds the scores up, returning the total.
    That's my code:
    class QuestionAnalyser{
    public static int Score;
    public String[] Answer;
    public static void main(String[] args) {}
         public int turnAnswerToScore(String[] Answer)
    for (int i = 0; i < Answer.length;i++) {
    if (Answer.equals("A")) {
    Score = Score + 1; }
    else if (Answer[i].equals("B")) {
    Score = Score + 2;}
    else if (Answer[i].equals("C")) {
    Score = Score + 3;}
    else {
    Score = Score + 0;}
    return Score;
    this is the error message I get:
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    QATest2.java:15: cannot resolve symbol
    symbol : method turnAnswersToScore (java.lang.String[])
    location: class QuestionAnalyser
    if(qa.turnAnswersToScore(task)!=total){
    ^
    What went wrong?
    Suggestions would be greatly appreciated!

    If I declare int score in the method i get this message
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ./QuestionAnalyser.java:20: variable score might not have been initialized
    score++; }
    ^
    ./QuestionAnalyser.java:23: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:27: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:34: variable score might not have been initialized
    return score;
    ^
    4 errors
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    Exception in thread "main" java.lang.NoClassDefFoundError: QuestionAnalyser
         at QATest2.main(QATest2.java:4)
    This is the message I get from the submission page, but trying to compile it I get the same messages.
    The code looks like this, then
    class QuestionAnalyser{
    String[] answer;
    public static void main(String[] args) {}
         public int turnAnswersToScore(String[] answer)
    int score;
    for (int i = 0; i < answer.length; i++) {
    if (answer.equals("A")) {
    score++; }
    else if (answer[i].equals("B")) {
    score++;
    score++; }
    else if (answer[i].equals("C")) {
    score++;
    score++;
    score++; }
    else {}
    return score;
    When I leave 'public int score;' where it was before (right after the class declaration below the declaration of the string array) I get this but it compiles normally.
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    wrong answer in turnAnswersToScore for
    BDCAADDCA
    Alright, even university students need to sleep :-)
    Good night.

  • Remove null values from string array

    Hi ,
    I have a string array in a jsp page which I save some values inside. After I store the values I want to print only those who are not null. How can I do this? Is there a way to delete the null values?

    Thank you but because I am new in programming what do you mean to use continue. Can you explain it a little bit further?<%
    //go through the array to check all the values
    for(int i=0; i<array.length();i++) {
    //If array is null, nothing happen
    if(array==null){
    //leave here blank; instead use continue like:
    //this will skip the statements next to it, and increments the value of i in for loop and continues to execute the body of for loop.
    //The same will be repeated till the last iteration.
    continue;
    //If array not null, then print value in a new line
    else{
    out.print(array+"<br>"); //don't change the logic here
    %>

Maybe you are looking for

  • Adobe cloud and CS6 not working

    Hi im unable to get cs6 to work for me using cloud? it keeps telling me my trial is over even though ive paid every month since June last year? ive tried deleting and reinstalling ect ect help!! there is no point me having this if i cant use it x

  • Consume Sales Order webservice in CRM 7.0

    Hello Experts, Basically I am an ABAP/XI expert, I have never used CRM. But I have a business case where in I need to consume Sales Order (Create) webservice to create one on to CRM. Please provide me with some Doc's, which talks about the webservice

  • Multiple airport express units/multiple speakers

    I saw a question and answer on this and now can't find it: I have two Express units on an Extreme network, want to stream the same iTunes signal to both of them (big house, two stereos.) How do I do this? iMac Intel Dual Core   Mac OS X (10.4.6)  

  • Bug in full screen slide show: Speed-values under 1.0 don't work, they will be zero. Maybe a german problem because of ","?

    I wan't to do a full screen slide show with changing images under one second. But this doesn't work because every value under 1 will be 0. Maybe this is a german problem because we use "," instead of a ".". But I can't use ".", the field doesn't allo

  • DTW 2005 and User table

    Hi all, I just want to know if DTW can be used to import data in user table. I think it's possible as you can choose the table in the list of objec to import. But I have an error when I try to import data. For example, a simple user table with the fi