Java Program to Create a Vector to Store Objects of a Class

You are currently viewing Java Program to Create a Vector to Store Objects of a Class

Java program to create a vector to store objects of a class

// Java program to create a vector to 
// store objects of a class

import java.util.*;

class Complex {
  int real;
  int imaginary;

  Complex(int r, int i) {
    this.real = r;
    this.imaginary = i;
  }

  void printComplex() {
    System.out.println("Complex Number: " + real + " + " + imaginary + "i");
  }
}

public class Main {
  public static void main(String[] args) {
    Vector < Complex > vec = new Vector < Complex > ();

    vec.add(new Complex(10, 11));
    vec.add(new Complex(20, 21));
    vec.add(new Complex(30, 31));
    vec.add(new Complex(40, 41));

    System.out.println("Vector Elements:");
    for (Complex c: vec) {
      c.printComplex();
    }
  }
}

Output

Vector Elements:
Complex Number: 10 + 11i
Complex Number: 20 + 21i
Complex Number: 30 + 31i
Complex Number: 40 + 41i

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply