Vimzy
Vimzy

Reputation: 1965

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? I'm quite confused. Thoughts guys?

Upvotes: 2

Views: 1089

Answers (2)

user3360944
user3360944

Reputation: 558

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

Upvotes: 0

user695992
user695992

Reputation:

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.

Upvotes: 4

Related Questions