Java Program to Create a Vector to Store Different Types of Objects

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

Java program to create a vector to store different types of objects

// Java program to create a vector to store 
// different types of objects

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(real + " + " + imaginary + "i");
  }
}

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

    vec.add(new Complex(10, 11));
    vec.add(new Complex(20, 21));
    vec.add(10);
    vec.add(20.5);
    vec.add(true);

    System.out.println("Vector Elements:");
    for (Object obj: vec) {
      if (obj instanceof Complex)
        ((Complex) obj).printComplex();
      else
        System.out.println(obj + "");
    }
  }
}

Output

Vector Elements:
10 + 11i
20 + 21i
10
20.5
true

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