When do we use Stack<Integer> st = new Stack<Integer>(); and when to use Stack st = new Stack();?

huangapple go评论69阅读模式
英文:

When do we use Stack<Integer> st = new Stack<Integer>(); and when to use Stack st = new Stack();?

问题

在Java中,何时使用

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

以及何时使用

Stack st = new Stack();

对于Stack st = new Stack(),我将不得不创建自己的Stack类,除此之外它们之间还有其他特定的区别吗?

英文:

In Java, when to use

Stack&lt;Integer&gt; st = new Stack&lt;Integer&gt;();

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?

答案1

得分: 2

> 什么时候使用 Stack st = new Stack();

从不。这种风格早于 Java 中的泛型存在。它完全被泛型用法取代,即 Stack&lt;Integer&gt;。有时候你需要使用延迟绑定,并且不知道堆栈内将存储哪种类型。但即使在这种情况下,你也应该使用通配符,比如 Stack&lt;?&gt;

现代集成开发环境(IDE)会在你使用没有指定泛型参数的泛型类时发出警告。

> 我将不得不创建我自己的类 Stack

你不需要这样做,你可以将泛型的 Stack 类(即 java.util.Stack&lt;T&gt;)以非泛型方式使用。Java 允许这样做(对于任何泛型类,不仅仅是 Stack)。但这是不鼓励的,参见上文。

英文:

> 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&lt;Integer&gt;. 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&lt;?&gt;.

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&lt;T&gt;) non-generically. Java allows that (for any generic class, not just for Stack). But it’s discouraged, see above.

huangapple
  • 本文由 发表于 2020年9月13日 18:13:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63869580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定