简体   繁体   English

初始化Java中的通用变量?

[英]Initializing Generic Variables in Java?

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? 然后我可以将其传递给push方法吗? I'm quite confused. 我很困惑 Thoughts guys? 大家好吗?

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时,请提供以下类型:

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. 初始化类的任何类型就是传递给方法的变量的类型。

You stated that T was a Number 您说T是一个数字

public class NumberStack<T extends Number> {
   public void push(T element) {
     // now you can add Number specific functionality here
   }
}

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

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