问题
I'm having trouble working with generics. I have a method as
public void push (T element)
Now what I'm having trouble understanding is how to create a generic variable so that I can pass it into that method. I know that the generic will always be a number, but I'm not getting how I should do that. Would it have to be something like
T number = 5
And then would I be able to pass that into the push method? I'm quite confused. Thoughts guys?
回答1:
You stated that T was a Number
public class NumberStack<T extends Number> {
public void push(T element) {
// now you can add Number specific functionality here
}
}
回答2:
You aren't working with a generic variable persay. Your code would look like this:
public class Stack<T> {
public void push(T element) {
}
}
When you go to initialize Stack you provide the type:
Stack<String> stack = new Stack<String>();
stack.push("hello");
Whatever you initialize the type for the class is the type of variable you pass to your method.
来源:https://stackoverflow.com/questions/22340383/initializing-generic-variables-in-java