beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to convert Vector to String array in java

By Chaitanya Singh | Filed Under: Java Collections

Couple of weeks back we shared a tutorial on ArrayList to String Array conversion. In this tutorial, we are gonna see how to convert a Vector to String Array in Java.

Example

Lets have a look at the below example where we are converting a Vector of Strings to an array. We are using toString() method of Vector class to do this.
public String toString(): It returns a string representation of this Vector, containing the String representation of each element.

import java.util.Vector;
public class VectorToArray {
 
  public static void main(String[] args) {
 
     // Creating a Vector of String elements
     Vector<String> vector = new Vector<String>();
 
     // Add elements to Vector
     vector.add("Item1");
     vector.add("Item2");
     vector.add("Item3");
     vector.add("Item4");
     vector.add("Item5");
     vector.add("Item6");
 
    //Converting Vector to String Array
    String[] array = vector.toArray(new String[vector.size()]);
 
    //Displaying Array Elements
    System.out.println("String Array Elements :");
    for(int i=0; i < array.length ; i++){
       System.out.println(array[i]);
    }
  }
}

Output:

String Array Elements :
Item1
Item2
Item3
Item4
Item5
Item6

The steps we followed in above code are:
1) Created a Vector of type String
2) Added elements to it using add(Element E) method of Vector class.
3) Converted the Vector to Array using toArray(new String[vector.size()]).

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap