Home » Java programming language

Java Vector toArray() Method with Example

Vector Class toArray() method: Here, we are going to learn about the toArray() method of Vector Class with its syntax and example.
Submitted by Preeti Jain, on March 20, 2020

Vector Class toArray() method

Syntax:

    public Object[] toArray();
    public Object[] toArray(Type[] ty);
  • toArray() method is available in java.util package.
  • toArray() method is used to return an array of elements that exists in this Vector.
  • toArray(Type[] ty) method is used to return an array that holds all the existing elements in this vector.
  • These methods may throw an exception at the time of representing an array.
    • ArrayStoreException: This exception may throw when the given parameter is not in a range.
    • NullPointerException: This exception may throw when the given parameter is null exists.
  • These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.

Parameter(s):

  • In the first case, toArray()
    • It does not accept any parameters.
  • In the first case, toArray(Type[] ty)
    • Type[] ty – represents the array where we have to store all existing elements of this Vector.

Return value:

In the first case, the return type of the method is Object [] – It returns an object array (Object []) that hold all elements exists in this vector.

In the second case, the return type of the method is Type [] – It returns an array of same type that holds vector elements.

Example:

// Java program to demonstrate the example 
// of toArray() method of Vector

import java.util.*;

public class ToArrayOfVector {
 public static void main(String[] args) {
  // Instantiates a vector object  
  String[] s = {};
  Vector < String > v = new Vector < String > (Arrays.asList(s));

  String[] str = new String[5];

  // By using add() method is to add
  // the elements in vector
  v.add("C");
  v.add("C++");
  v.add("SFDC");
  v.add("JAVA");

  //Display Vector
  System.out.println("v: " + v);

  // By using toArray() method is to
  // return an array that contains all the 
  // vector elements
  str = v.toArray(str);

  System.out.println("v.toArray(): ");

  for (int i = 0; i < str.length; ++i)
   System.out.println(str[i]);

  // By using toArray(array) method is to
  // return an array that contains all the 
  // vector elements by using an array
  v.toArray(str);

  System.out.println("v.toArray(str): ");
  for (int i = 0; i < str.length; ++i)
   System.out.println(str[i]);
 }
}

Output

v: [C, C++, SFDC, JAVA]
v.toArray(): 
C
C++
SFDC
JAVA
null
v.toArray(str): 
C
C++
SFDC
JAVA
null



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.