0

I'd like to implement Stack from scratch and encountered a problem. I feel like I'm writing the parameters for push method wrong such as:

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

How else can I write the parameter when I'm not sure what type the foo is going to be?

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);
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269

4 Answers4

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

You can read more on generics here.

Emile Pels
  • 3,837
  • 1
  • 15
  • 23
0

The correct syntax is :

public void push(T foo) {
    myList.add(foo);
}
ttzn
  • 2,543
  • 22
  • 26
0

It just needs to be

public void push(T foo){
    myList.add(foo);
}
user007
  • 2,156
  • 2
  • 20
  • 35
-5

Type cast foo to Object type

public void push(Object foo){
    myList.add(foo);
}
katwekibs
  • 1,342
  • 14
  • 17
  • 4
    Terrible solution. He's using generics. Making push take `Object` just disables the type safety he can get from the generic solution. – Erick G. Hagstrom Jul 26 '15 at 19:42