0

In Java, when to use

Stack<Integer> st = new Stack<Integer>();

and when to use

Stack st  = new Stack();

For Stack st = new Stack(), I will have to create my own class Stack, other than this is there any other specific differences between them?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Nupur
  • 87
  • 6
  • "*For `Stack st = new Stack()` I will have to create my own class Stack*" can you provide more details about your reasoning here? – Pshemo Sep 13 '20 at 10:24
  • Feel free to use [edit] option to correct/clarify that *in the question itself*. – Pshemo Sep 29 '20 at 17:17

1 Answers1

2

when to use Stack st = new Stack();?

Never. That style predates the existence of generics in Java. It’s completely replaced by generic usage, i.e. Stack<Integer>. Sometimes you need to use late binding and don’t know which type will be stored inside the stack. But even then you’re supposed to use wildcards, i.e. something like Stack<?>.

A modern IDE will warn you if you use a generic class without specifying generic parameters.

I will have to create my own class Stack

You don’t, you could use the generic Stack class (that is, java.util.Stack<T>) non-generically. Java allows that (for any generic class, not just for Stack). But it’s discouraged, see above.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214