×

Java Programs

Java Practice

Java program to add elements of a vector to other vector collection at the specified position

Java example to add elements of a vector to other vector collection at the specified position.
Submitted by Nidhi, on May 19, 2022

Problem statement

In this program, we will create two Vector collection with different types of elements. Then we will add a vector collection to another vector at a specified position using the addAll() method.

Java program to add elements of a vector to other vector collection at the specified position

The source code to add elements of a vector to other vector collection at a specified position is given below. The given program is compiled and executed successfully.

// Java program to add elements of a vector to other 
// vector collection at the specified position

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Vector vec1 = new Vector();
    Vector vec2 = new Vector();

    vec1.add(10);
    vec1.add(20.5);
    vec1.add(true);
    vec1.add("Hello World");

    vec2.add("A");
    vec2.add("B");
    vec2.add("C");
    vec2.add("D");

    System.out.println("Vector Vec1 : " + vec1);
    System.out.println("Vector Vec2 : " + vec2);

    vec1.addAll(2, vec2);

    System.out.println("\nVector Vec1 : " + vec1);
    System.out.println("Vector Vec2 : " + vec2);
  }
}

Output

Vector Vec1 : [10, 20.5, true, Hello World]
Vector Vec2 : [A, B, C, D]

Vector Vec1 : [10, 20.5, A, B, C, D, true, Hello World]
Vector Vec2 : [A, B, C, D]

Explanation

In the above program, we imported the "java.util.*" package to use the Vector class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created two Vector collections vec1, vec2 and add elements to them. Then we added vec2 vector to vec1 at index 2 using addAll() method. After that, we printed the updated vectors.

Java Vector Class Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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