英文:
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
英文:
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
答案1
得分: 4
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);
}
}
英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论