Initializing Generic Variables in Java?

无人久伴 提交于 2021-02-10 05:01:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!