Write a Java program to Create a set of Complex numbers using HashSet collections


The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet.

  • The program defines a public class called Complex_Numbers. Within the Complex_Numbers class, the main method is declared and serves as the entry point for the program. It takes an array of strings (args) as input.
  • Inside the main method, a new instance of the HashSet class is created using the constructor: HashSet<Complex> comp = new HashSet<Complex>();. The <Complex> specifies the type of elements that will be stored in the HashSet, which in this case is an object of the Complex class.
  • After that, several Complex objects are created using the Complex class constructor, and they are added to the comp HashSet using the add() method. Each Complex object represents a complex number with a real part and an imaginary part.
  • The program then uses a foreach loop to iterate over the elements of the comp HashSet. Inside the loop, the printComplex() method is called on each Complex object to print the complex number in the format "Complex Number: <real part> + <imaginary part>i".
  • The Complex class is defined separately below the Complex_Numbers class. It has two instance variables: re to store the real part of the complex number and img to store the imaginary part. It also has a constructor that initializes the instance variables with the provided values.
  • The printComplex() method is defined within the Complex class, and it prints the complex number in the desired format using the System.out.println() statement.

Source Code

import java.util.*;
public class Complex_Numbers
{
	public static void main(String[] args)
	{
		HashSet<Complex> comp = new HashSet<Complex>();
		comp.add(new Complex(10, 20));
		comp.add(new Complex(20, 30));
		comp.add(new Complex(30, 40));
		comp.add(new Complex(40, 50));
		comp.add(new Complex(50, 60));
 
		System.out.println("Hash Set of Complex Numbers.. ");
		for (Complex c: comp) 
		{
			c.printComplex();
		}
	}
}
class Complex 
{
	int re;
	int img;
 
	Complex(int r, int i) 
	{
		this.re = r;
		this.img = i;
	}
 
	void printComplex()
	{
		System.out.println("Complex Number: " + re + " + " + img + "i");
	}
}

Output

Hash Set of Complex Numbers..
Complex Number: 40 + 50i
Complex Number: 50 + 60i
Complex Number: 10 + 20i
Complex Number: 30 + 40i
Complex Number: 20 + 30i

Example Programs