java中的集合框架需要什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2497134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:27:44  来源:igfitidea点击:

What is the need of collection framework in java?

javacollections

提问by JavaUser

What is the need of Collection framework in Java since all the data operations(sorting/adding/deleting) are possible with Arrays and moreover array is suitable for memory consumption and performance is also better compared with Collections.

Java中的Collection框架需要什么,因为所有的数据操作(排序/添加/删除)都可以用Arrays进行,而且arrays适合内存消耗并且与Collection相比性能也更好。

Can anyone point me a real time data oriented example which shows the difference in both(array/Collections) of these implementations.

任何人都可以向我指出一个实时面向数据的示例,该示例显示了这些实现的两个(数组/集合)的差异。

采纳答案by Chris Jester-Young

  • Arrays are not resizable.
  • Java Collections Framework provides lots of different useful data types, such as linked lists (allows insertion anywhere in constant time), resizeable array lists (like Vectorbut cooler), red-black trees, hash-based maps (like Hashtablebut cooler).
  • Java Collections Framework provides abstractions, so you can refer to a list as a List, whether backed by an array list or a linked list; and you can refer to a map/dictionary as a Map, whether backed by a red-black tree or a hashtable.
  • 数组不可调整大小。
  • Java Collections Framework 提供了许多不同的有用数据类型,例如链表(允许在恒定时间内在任何地方插入)、可调整大小的数组列表(类似Vector但更酷)、红黑树、基于哈希的映射(类似Hashtable但更酷)。
  • Java Collections Framework 提供了抽象,因此您可以将列表称为List,无论是由数组列表还是链表支持;并且您可以将地图/字典称为 a Map,无论是由红黑树还是哈希表支持。

In other words, Java Collections Framework allows you to use the right data structure, because one size does not fit all.

换句话说,Java Collections Framework 允许您使用正确的数据结构,因为一种大小不能适应所有情况。

回答by Drew Wills

Collection classes like Set, List, and Map implementations are closer to the "problem space." They allow developers to complete work more quickly and turn in more readable/maintainable code.

集合类(如 Set、List 和 Map 实现)更接近“问题空间”。它们允许开发人员更快地完成工作并提交更具可读性/可维护性的代码。

回答by Justin Ethier

It depends upon your application's needs. There are so many types of collections, including:

这取决于您的应用程序的需求。有很多类型的集合,包括:

  • HashSet
  • ArrayList
  • HashMap
  • TreeSet
  • TreeMap
  • LinkedList
  • 哈希集
  • 数组列表
  • 哈希表
  • 树集
  • 树形图
  • 链表

So for example, if you need to store key/value pairs, you will have to write a lot of custom code if it will be based off an array - whereas the Hash* collections should just work out of the box. As always, pick the right tool for the job.

因此,例如,如果您需要存储键/值对,如果它基于数组,您将不得不编写大量自定义代码 - 而 Hash* 集合应该开箱即用。一如既往,为工作选择合适的工具。

回答by Itay Maman

Several reasons:

几个原因:

  • Java's collection classes provides a higher level interface than arrays.
  • Arrays have a fixed size. Collections (see ArrayList) have a flexible size.
  • Efficiently implementing a complicated data structures (e.g., hash tables) on top of raw arrays is a demanding task. The standard HashMap gives you that for free.
  • There are different implementation you can choose from for the same set of services: ArrayList vs. LinkedList, HashMap vs. TreeMap, synchronized, etc.
  • Finally, arrays allow covariance: setting an element of an array is not guaranteed to succeed due to typing errors that are detectable only at run time. Generics prevent this problem in arrays.
  • Java 的集合类提供了比数组更高级别的接口。
  • 数组具有固定大小。集合(请参阅 ArrayList)具有灵活的大小。
  • 在原始数组之上有效地实现复杂的数据结构(例如,哈希表)是一项艰巨的任务。标准的 HashMap 免费为您提供。
  • 您可以为同一组服务选择不同的实现:ArrayList 与 LinkedList、HashMap 与 TreeMap、synchronized 等。
  • 最后,数组允许协方差:由于输入错误只能在运行时检测到,因此不能保证设置数组元素会成功。泛型可防止数组中出现此问题。

Take a look at this fragment that illustrates the covariance problem:

看看这个说明协方差问题的片段:

  String[] strings = new String[10];
  Object[] objects = strings;

  objects[0] = new Date();  // <- ArrayStoreException: java.util.Date

回答by Jonathan Feinberg

For each class in the Collections API there's a different answer to your question. Here are a few examples.

对于 Collections API 中的每个类,您的问题都有不同的答案。这里有一些例子。

LinkedList: If you remove an element from the middle of an array, you pay the cost of moving all of the elements to the right of the removed element. Not so with a linked list.

LinkedList:如果您从数组中间移除一个元素,您需要支付将所有元素移动到被移除元素右侧的成本。链表不是这样。

Set: If you try to implement a set with an array, adding an element or testing for an element's presence is O(N). With a HashSet, it's O(1).

集合:如果您尝试使用数组实现集合,则添加元素或测试元素是否存在的过程是 O(N)。使用 HashSet,它是 O(1)。

Map: To implement a map using an array would give the same performance characteristics as your putative array implementation of a set.

映射:使用数组实现映射将提供与集合的假定数组实现相同的性能特征。

回答by TofuBeer

Well the basic premise is "wrong" since Java included the Dictionary class since before interfaces existed in the language...

那么基本前提是“错误的”,因为 Java 包含 Dictionary 类,因为在语言中存在接口之前......

collections offer Lists which are somewhat similar to arrays, but they offer many more things that are not. I'll assume you were just talking about List (and even Set) and leave Map out of it.

集合提供了有点类似于数组的列表,但它们提供了更多不是的东西。我假设您只是在谈论 List(甚至 Set),而将 Map 排除在外。

Yes, it is possible to get the same functionality as List and Set with an array, however there is a lot of work involved. The whole point of a library is that users do not have to "roll their own" implementations of common things.

是的,使用数组可以获得与 List 和 Set 相同的功能,但是需要做很多工作。库的全部意义在于用户不必“推出自己的”常见事物的实现。

Once you have a single implementation that everyone uses it is easier to justify spending resources optimizing it as well. That means when the standard collections are sped up or have their memory footprint reduced that all applications using them get the improvements for free.

一旦你有一个每个人都使用的单一实现,就更容易证明花费资源优化它的合理性。这意味着当标准集合加速或内存占用减少时,所有使用它们的应用程序都可以免费获得改进。

A single interface for each thing also simplifies every developers learning curve - there are not umpteen different ways of doing the same thing.

每件事情的单一界面也简化了每个开发人员的学习曲线 - 做同样的事情没有无数不同的方法。

If you wanted to have an array that grows over time you would probably not put the growth code all over your classes, but would instead write a single utility method to do that. Same for deletion and insertion etc...

如果您想要一个随时间增长的数组,您可能不会将增长代码放在所有类中,而是编写一个实用程序方法来实现这一点。删除和插入等相同...

Also, arrays are not well suited to insertion/deletion, especially when you expect that the .length member is supposed to reflect the actual number of contents, so you would spend a huge amount of time growing and shrinking the array. Arrays are also not well suited for Sets as you would have to iterate over the entire array each time you wanted to do an insertion to check for duplicates. That would kill any perceived efficiency.

此外,数组不太适合插入/删除,尤其是当您期望 .length 成员应该反映实际内容数量时,因此您将花费大量时间来增加和缩小数组。数组也不太适合集合,因为每次要进行插入以检查重复项时都必须遍历整个数组。这将扼杀任何感知效率。

回答by fastcodejava

Arrays are not efficient always. What if you need something like LinkedList? Looks like you need to learn some data structure : http://en.wikipedia.org/wiki/List_of_data_structures

数组并不总是有效的。如果你需要类似的东西LinkedList怎么办?看起来你需要学习一些数据结构:http: //en.wikipedia.org/wiki/List_of_data_structures

回答by girish lalwani

Collection is the framework in Java and you know that framework is very easy to use rather than implementing and then use it and your concern is that why we don't use the array there are drawbacks of array like it is static you have to define the size of row at least in beginning, so if your array is large then it would result primarily in wastage of large memory. So you can prefer ArrayList over it which is inside the collection hierarchy.

Collection 是 Java 中的框架,您知道该框架非常易于使用,而不是实现然后使用它,您担心的是为什么我们不使用数组,数组有一些缺点,例如它是静态的,您必须定义至少在开始时行的大小,所以如果你的数组很大,那么它主要会导致大内存的浪费。所以你可以更喜欢 ArrayList 而不是它在集合层次结构中。

Complexity is other issue like you want to insert in array then you have to trace it upto define index so over it you can use LinkedList all functions are implemented only you need to use and became your code less complex and you can read there are various advantages of collection hierarchy.

复杂性是另一个问题,例如您想插入数组,然后您必须跟踪它以定义索引,因此您可以使用 LinkedList 所有功能都实现了,只有您需要使用,并且您的代码变得不那么复杂,您可以阅读有各种优点集合层次结构。

回答by VdeX

Java Collectionscame up with different functionality,usability and convenience.

Java Collections提供了不同的功能、可用性和便利性。

When in an application we want to work on group of Objects, Only ARRAY can not help us,Or rather they might leads to do things with some cumbersome operations.

当在一个应用程序中我们想要处理一组对象时,只有 ARRAY 帮不了我们,或者说他们可能会导致做一些繁琐的操作。

One important difference, is one of usability and convenience, especially given that Collections automatically expand in size when needed:

一个重要的区别是可用性和便利性之一,特别是考虑到集合在需要时会自动扩展大小:

Collections came up with methods to simplify our work.

集合提出了简化我们工作的方法。

Each one has a unique feature:

每个都有一个独特的功能:

  • List-Essentially a variable-size array;
    You can usually add/remove items at any arbitrary position;
    The order of the items is well defined (i.e. you can say what position a given item goes in in the list).

    Used- Most cases where you just need to store or iterate through a "bunch of things" and later iterate through them.

  • Set-Things can be "there or not"— when you add items to a set, there's no notion of how many times the item was added, and usually no notion of ordering.

    Used-Remembering "which items you've already processed", e.g. when doing a web crawl;
    Making other yes-no decisions about an item, e.g. "is the item a word of English", "is the item in the database?" , "is the item in this category?" etc.

  • List——本质上是一个可变大小的数组;
    您通常可以在任意位置添加/删除项目;
    项目的顺序是明确定义的(即您可以说出给定项目在列表中的位置)。

    使用- 大多数情况下,您只需要存储或迭代“一堆东西”,然后再迭代它们。

  • 设置-事物可以“存在或不存在”——当您向集合中添加项目时,没有关于该项目添加了多少次的概念,并且通常没有排序的概念。

    使用 -记住“您已经处理过哪些项目”,例如在进行网络抓取时;
    对某个项目做出其他是-否决定,例如“该项目是英语单词吗”、“该项目是否在数据库中?” , “该商品在这个类别中吗?” 等等。

Here you find use of each collection as per scenario:

在这里,您可以根据场景找到每个集合的使用

回答by Johnny

Collection framework are much higher level compared to Arraysand provides important interfaces and classes that by using them we can manage groups of objects with a much sophisticated way with many methods already given by the specific collection.

与数组相比,集合框架的级别要高得多,并提供了重要的接口和类,通过使用它们,我们可以使用特定集合已经提供的许多方法,以非常复杂的方式管理对象组。

For example:

例如:

  • ArrayList - It's like a dynamic array i.e. we don't need to declare its size, it grows as we add elements to it and it shrinks as we remove elements from it, during the runtime of the program.
  • LinkedList - It can be used to depict a Queue(FIFO) or even a Stack(LIFO).
  • HashSet - It stores its element by a process called hashing. The order of elements in HashSet is not guaranteed.
  • TreeSet - TreeSet is the best candidate when one needs to store a large number of sorted elements and their fast access.
  • ArrayDeque - It can also be used to implement a first-in, first-out(FIFO) queue or a last-in, first-out(LIFO) queue.
  • HashMap - HashMap stores the data in the form of key-value pairs, where key and value are objects.
  • Treemap - TreeMap stores key-value pairs in a sorted ascending order and retrieval speed of an element out of a TreeMap is quite fast.
  • ArrayList - 它就像一个动态数组,即我们不需要声明它的大小,它随着我们向它添加元素而增长,随着我们从中删除元素而缩小,在程序运行期间。
  • LinkedList - 它可用于描述队列(FIFO)甚至堆栈(LIFO)。
  • HashSet - 它通过称为散列的过程存储其元素。HashSet 中元素的顺序无法保证。
  • TreeSet - 当需要存储大量排序元素及其快速访问时,TreeSet 是最佳候选者。
  • ArrayDeque - 它还可以用于实现先进先出 (FIFO) 队列或后进先出 (LIFO) 队列。
  • HashMap - HashMap 以键值对的形式存储数据,其中键和值是对象。
  • Treemap - TreeMap 以升序排序存储键值对,并且从 TreeMap 中检索元素的速度非常快。

To learn more about Java collections, check out this article.

要了解有关 Java 集合的更多信息,请查看这篇文章