Tasneem
Tasneem

Reputation: 101

Implementing Stack With (Key,Value)

I am wondering if I can implement a stack with (Key, Value) like below:

    public static void main(String[] args) {
    PriorityQueueStack<Integer,V> s = new PriorityQueueStack<>();
    s.push(1,'A');
    s.push(2,'B');
    s.push(3,'C');
    s.push(4,'D');

My class implementation is like below:

  public class PriorityQueueStack<E> extends SortedPriorityQueue<Integer, E> implements 
  PriorityQueue<Integer, E>{

Is there a way to implement it with (Key, Value) as I have searched I couldn't find any resource of such an implementation.

The output should be like this:

 (1,'A'),(2,'B')..... and so on

Upvotes: 1

Views: 3751

Answers (1)

Yash Shah
Yash Shah

Reputation: 1654

It could be done by creating a separate class for key-value pair and adding an object of that class in the Stack.

class Pair{
    
    int key;
    char value;
    
    public Pair(int key,char value){
        this.key = key;
        this.value = value;
    }
    
}


public class Main {
    public static void main(String[] args) {
        Stack<Pair> stack = new Stack<>();
        stack.push(new Pair(1,'A'));
        stack.push(new Pair(2,'B'));
        stack.push(new Pair(3,'C'));
        stack.push(new Pair(4,'D'));
        // Pair p = stack.pop();
        // System.out.println(p.key+" "+p.value);
    }
}

Upvotes: 5

Related Questions