Class SortedStack

java.lang.Object
SortedStack

public class SortedStack extends Object
Represents a sorted stack of integers. The stack is created from a comma-separated string of integers.
 How to Run:

 javac -d bin *.java
 java -cp bin SortedStack.java
 
 Command Used to create Javadocs:

 javadoc -d docs *.java
 

Almost the entire class is reused between the week 4 and week 5 assignments.

The changes are:

  • 1) Converting the instance variable from a LinkedList<Integer> to Stack<Integer>
  • 2) Changing the return types of the getter and private utility method from LinkedList<Integer> to Stack<Integer>
  • 3) Passing Stack::new instead of LinkedList::new to Collectors.toCollection()

All other changes are updating comments, javadocs, etc. to reference Stack instead of LinkedList

If this was something that was often changing, I'd likely rewrite the class as a generic where the collection type was passed in on creation.

  • Constructor Details

    • SortedStack

      public SortedStack(String integerString)
      Constructs a SortedStack from a comma-separated string of integers. If the string is null or empty, an empty stack is created. If the string cannot be parsed, an error is printed.
      Parameters:
      integerString - A string containing comma-separated integers.
  • Method Details

    • getSortedStack

      public Stack<Integer> getSortedStack()
      Getter for the sorted stack.
      Returns:
      A sorted Stack of integers or null if the integer string was unable to be parsed.
    • toString

      public String toString()
      Returns a string representation of the sorted stack.
      Overrides:
      toString in class Object
      Returns:
      A string representation of the stack, e.g., "[1, 2, 3]".
    • main

      public static void main(String[] args)
      The main method to demonstrate the SortedStack functionality. Prompts the user to enter a comma-separated string of integers, creates a SortedStack, and prints it.
      Parameters:
      args - Command line arguments (not used).