ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.