从头开始实现`Stack`

时间:2015-07-26 19:39:10

标签: java

我想从头开始实施Stack并遇到问题。我觉得我在编写push方法的参数错误,例如:

public void push(<T> foo){
    myList.add(foo);
}

当我不确定foo将是什么类型时,我还能如何编写参数?

package Stack;
import java.util.*;

public class Stack<T> {

    private List<T> myList;

    public Stack(){
        myList = null;
    }

    public boolean empty(){
        return (myList == null);
    }

    public void push(<T> foo){
        myList.add(foo);
    }
}

4 个答案:

答案 0 :(得分:4)

public void push(T foo){
    myList.add(foo);
}

您可以阅读有关泛型here的更多信息。

答案 1 :(得分:0)

正确的语法是:

public void push(T foo) {
    myList.add(foo);
}

答案 2 :(得分:0)

只需要

static struct Point{
public:
    double x, y;
    std::set<std::multiset<Point>*,PointerCompare>occurrences;

    Point(double a, double b){ x = a; y = b; }
    Point(){}
};

struct PointerCompare{
    bool operator()(std::multiset<Point>* a, std::multiset<Point>* b){
        uintptr_t aVal = reinterpret_cast<uintptr_t>(a);
        uintptr_t bVal = reinterpret_cast<uintptr_t>(b);
        return a < b;
    }
};

答案 3 :(得分:-5)

键入cast foo到Object type

public void push(Object foo){
    myList.add(foo);
}