【问题标题】:Java: Vector sort vs Collection sortJava:向量排序与集合排序
【发布时间】:2015-05-28 13:11:35
【问题描述】:

我从来没有愉快地使用下面的代码,现在我偶然发现了一个作业,我想在其中争论哪些是最常用的,以及为什么。

我们有两个例子,

public Vector<Integer> sort(Vector<Integer> integers) { ... }

public Collection<Integer> sort(Collection<Integer> integers) {}

本质上,我们要争论这两个示例中哪一个是对事物进行排序的最佳解决方案。这两个中哪一个用得最多,为什么?

【问题讨论】:

  • 矢量已过时。使用集合
  • @aTON 我认为您应该考虑答案,而不是在 stackoverflow 上提问。
  • As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.
  • Vector的API文档如是说。 (这应该是您真正的第一个呼叫端口。)我个人会补充说,即使需要线程安全的实现,您也应该避免使用Vector。
  • Vector 使用同步,这在大多数情况下是不需要的,并且会影响性​​能

标签: java sorting vector collections


【解决方案1】:

本质上,我们要争论这两个示例中哪一个是对事物进行排序的最佳解决方案。这两个中哪一个用得最多,为什么?

很多 cmets,但我真的没有看到答案。所以:第二个现在更常用。第一个是一种旧方法,可以追溯到早期的 Java 时代。您仍然可以使用它,但现在人们主要使用第二个,因为它显然对使用它的人提出了较少的要求(特别是您正在排序的集合不需要是Vector)。

【讨论】:

    【解决方案2】:

    各有优缺点。我认为你被要求在两个糟糕的选择之间做出选择(也许是故意的)。

    正如许多人已经说过的,Vector 已经过时了。不应该使用它。

    但是……Collections.sort 方法采用 List 而不是 Collection 是有原因的:如何对无序 Set 进行排序?如何对已经具有所需顺序的集合(如 TreeSet)进行排序?

    由于对集合进行排序的概念定义得很差,因此采用 Vector 的方法可能更好用,即使不应该使用 Vector 本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 2010-09-29
      相关资源
      最近更新 更多