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


The code you provided is written in Java and demonstrates the usage of a Vector to store objects of a custom class called Complex. Here's a step-by-step explanation of the code:

  • import java.util.*;: This line imports the java.util package, which contains the Vector class and other utility classes.
  • public class Store_Objects: This line declares a public class named Store_Objects.
  • public static void main(String[] args): This is the main method where the execution of the program starts. It takes an array of strings as command line arguments.
  • Vector<Complex> vec_list = new Vector<Complex>();: This line declares and initializes a Vector object named vec_list that can store objects of type Complex. The Complex class is defined later in the code.
  • vec_list.add(new Complex(1, 6));: This line creates a new Complex object with the values 1 and 6 for the real and imaginary parts, respectively. The object is then added to the vector vec_list. This process is repeated for the next four Complex objects, each with different values.
  • for (Complex c: vec_list): This line starts a for-each loop that iterates over each element c in the vector vec_list. It assigns the current element to the variable c of type Complex.
  • c.printComplex();: Inside the for-each loop, this line calls the printComplex() method on each Complex object c. The method prints the real and imaginary parts of the complex number.
  • The Complex class is defined outside the main method. It contains two instance variables: real and ima, which represent the real and imaginary parts of a complex number.
  • Complex(int r, int i): This is the constructor of the Complex class. It takes two integer parameters, r and i, and assigns them to the real and ima instance variables, respectively.
  • void printComplex(): This method prints the complex number in the format "Complex Number: real + ima i", where real and ima are the values of the corresponding instance variables.

This indicates that the vector contains five Complex objects, and the printComplex() method is called on each object to display their values.

Source Code

import java.util.*;
public class Store_Objects
{
	public static void main(String[] args)
	{
		Vector <Complex> vec_list = new Vector <Complex>();
 
		vec_list.add(new Complex(1, 6));
		vec_list.add(new Complex(2, 7));
		vec_list.add(new Complex(3, 8));
		vec_list.add(new Complex(4, 9));
		vec_list.add(new Complex(5, 10));
 
		for (Complex c: vec_list)
		{
			c.printComplex();
		}
	}
}
class Complex
{
	int real;
	int ima;
 
	Complex(int r, int i)
	{
		this.real = r;
		this.ima = i;
	}
 
	void printComplex()
	{
		System.out.println("Complex Number : " + real + " + " + ima + "i");
	}
}

Output

Complex Number : 1 + 6i
Complex Number : 2 + 7i
Complex Number : 3 + 8i
Complex Number : 4 + 9i
Complex Number : 5 + 10i

Example Programs