简体   繁体   English

如何使此代码与泛型一起工作?

[英]How can I make this code work with generics?

I have some code that sorts a stack using only another stack (it's an interview question). 我有一些代码仅使用另一个堆栈对堆栈进行排序(这是一个采访问题)。 The code itself seems to work. 代码本身似乎起作用。 I'd like to implement it using generics, so that any kind of stack is sortable, under the following conditions: 我想使用泛型来实现它,以便在以下条件下任何类型的堆栈都是可排序的:

  1. The sort method remains static (I'd like to avoid parameterizing the entire class) sort方法保持静态(我想避免参数化整个类)
  2. I can use native comparator operators (like <) - I guess the parameterized type needs to implement Comparable . 我可以使用本机比较器运算符(例如<)-我猜参数化类型需要实现Comparable

Is this possible? 这可能吗?

Here's the code. 这是代码。

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);
    }
}

You are on the right way by mentioning Comparable. 提及可比性,您是对的。

Your method can be 您的方法可以是

static <T extends Comparable<T>>void sort(Stack<T> stack) {

And the comparison curr < stack.peek() replace by 并且比较curr <stack.peek()替换为

curr.compareTo(stack.peek()) < 0

Using comparator operators on Objects (wrapped primitives or not) is not possible in Java. 在Java中,无法在对象上使用比较器运算符(是否包装了原语)。 C++ support such a possibility. C ++支持这种可能性。 However, you can create a workaround by forceing the parameter type to implement Comparable. 但是,可以通过强制参数类型实现Comparable来创建解决方法。 Your signature should look like this: 您的签名应如下所示:

public <T extends Comparable<? super T>> static void sort(Stack<T> stack)

And to compare, use compareTo instead of native operators (which is not possible in Java): 为了进行比较,请使用compareTo而不是本机运算符(在Java中是不可能的):

obj1.compareTo(obj2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM