[英]How can I make this code work with generics?
我有一些代码仅使用另一个堆栈对堆栈进行排序(这是一个采访问题)。 代码本身似乎起作用。 我想使用泛型来实现它,以便在以下条件下任何类型的堆栈都是可排序的:
这可能吗?
这是代码。
import java.util.Stack;
public class StackSort {
static void sort(Stack<Integer> stack) {
Stack<Integer> tmp = new Stack<Integer>();
for (;;) {
int nswaps = 0;
while (!stack.isEmpty()) {
Integer curr = stack.pop();
if (!stack.isEmpty() && curr < stack.peek()) {
Integer next = stack.pop();
tmp.push(next);
tmp.push(curr);
++nswaps;
} else {
tmp.push(curr);
}
}
while (!tmp.isEmpty()) {
stack.push(tmp.pop());
}
if (nswaps == 0) {
break;
}
}
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(6);
stack.push(4);
stack.push(11);
stack.push(8);
stack.push(7);
stack.push(3);
stack.push(5);
System.out.println(stack);
StackSort.sort(stack);
System.out.println(stack);
}
}
提及可比性,您是对的。
您的方法可以是
static <T extends Comparable<T>>void sort(Stack<T> stack) {
并且比较curr <stack.peek()替换为
curr.compareTo(stack.peek()) < 0
在Java中,无法在对象上使用比较器运算符(是否包装了原语)。 C ++支持这种可能性。 但是,可以通过强制参数类型实现Comparable来创建解决方法。 您的签名应如下所示:
public <T extends Comparable<? super T>> static void sort(Stack<T> stack)
为了进行比较,请使用compareTo
而不是本机运算符(在Java中是不可能的):
obj1.compareTo(obj2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.