Created a stack and the push() method is not working

59 views Asked by At

My push method for my stack is not working and I do not understand why. Eclipse says the argument is not applicable for the primitive type for my Stack.

  Stack<Bracket> openingBrackets = new Stack<>();

  for (int position = 1; position <= text.length(); ++position) {

     char next = text.charAt(position - 1);

     if ( next == '(' || next == '[' || next == '{') {

         openingBrackets.push(next);

     }

     System.out.print(openingBrackets.pop());

  }

I'm expecting the (, [, { to get added to the stack

2

There are 2 answers

1
Ceviche On

In order to initialize or declare a Stack in Java you must specify the type within the carrots <>.

Java collections are generic and these brackets are used to define the type of the data stored inside. e.g. Stack<Integer>. In this case you're pushing characters so you have two options:

  1. Specify type: Stack<Character> openingBrackets = new Stack<Character>(); (Recommended)
  2. Type agnostic: Stack<Object> openingBrackets = new Stack<Object>();

Side note: only pop() if there are items in the stack. So be sure to check for that :)

1
皮皮今 On

I'm not very good at communicating in English, but you can try running the following code to see if it meets your needs

package org.example;

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        String text = "([{[[sad";
        Stack<Character> openingBrackets = new Stack<>();

        for (int position = 0; position < text.length(); position++) {
            char next = text.charAt(position);

            if (next == '(' || next == '[' || next == '{') {
                openingBrackets.push(next);
            }

        }

        openingBrackets.forEach(System.out::println);
    }


}