Java program to create a set of Complex numbers using HashSet collections

Given a HashSet collection, we have to create a set of Complex numbers using it.
Submitted by Nidhi, on May 12, 2022

Problem Solution:

In this program, we will create a Complex class that contains data members real, and imaginary. Then we will add objects of the Complex class to the HashSet collection. After that, we will print complex numbers.

Program/Source Code:

The source code to create a set of Complex numbers using HashSet collections is given below. The given program is compiled and executed successfully.

// Java program to create a set of Complex numbers 
// using HashSet collections

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) {
    HashSet < Complex > comp = new HashSet();

    comp.add(new Complex(10, 20));
    comp.add(new Complex(20, 30));
    comp.add(new Complex(30, 40));
    comp.add(new Complex(40, 50));

    System.out.println("Hash Set of Complex numbers: ");
    for (Complex c: comp) {
      c.printComplex();
    }
  }
}

Output:

Hash Set of Complex numbers: 
Complex Number: 10 + 20i
Complex Number: 40 + 50i
Complex Number: 30 + 40i
Complex Number: 20 + 30i

Explanation:

In the above program, we imported the "java.util.*" package to use the HashSet collection. Here, we created a public class Main and a Complex class. The Complex class contains data members real, and imaginary. The Main class contains a method main().

The main() method is the entry point for the program. Here, we created a set to store complex numbers using the HashSet collection. Then we added complex numbers to created set using add() method. After that, we printed the set elements.

Java HashSet Programs »





Comments and Discussions!

Load comments ↻





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