Q:

Java program to create a Stack collection of objects of a class

belongs to collection: Java Stack Programs

0

Java program to create a Stack collection of objects of a class

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will create a Complex class and then create the list of objects of the Complex class using Stack collection. Then we will add and print complex numbers.

Program/Source Code:

The source code to create a Stack collection of objects of a class is given below. The given program is compiled and executed successfully.

// Java program to create a Stack collection of 
// objects of a class

import java.util.*;

class Complex {
  int real, img;

  Complex(int r, int i) {
    real = r;
    img = i;
  }
}
public class Main {
  public static void main(String[] args) {
    int i = 0;
    Stack < Complex > stk = new Stack < Complex > ();

    stk.push(new Complex(10, 20));
    stk.push(new Complex(20, 30));
    stk.push(new Complex(30, 40));
    stk.push(new Complex(40, 50));

    System.out.println("Stack items: ");

    for (i = 0; i < 4; i++) {
      Complex C = stk.pop();
      System.out.println(C.real + " + " + C.img + "i");
    }
  }
}

Output:

Stack items: 
10 + 20i
20 + 30i
30 + 40i
40 + 50i

Explanation:

In the above program, we imported the "java.io.*" and "java.util.*" packages to use the Stack collection class. Here we created two classes Complex and Main. The complex class contains two data members real and img. And, created a constructor to initialize data members.

The Main class contains a main() method. The main() method is the entry point for the program.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to get the size of Stack collection... >>
<< Java program to convert a Stack collection into an...