What types of collections and their differences in java?

Asked

Viewed 5,399 times

17

There are many types of java collections and I have difficulty knowing the following questions presented below:

  • What are the differences between them?
  • What situations and/or cases should I use each of the different collections?
  • 2

    Your question can be answered in the official documentation, the differences being: http://docs.oracle.com/javase/tutorial/collections/implementations/index.html and use: http://docs.oracle.com/javase/tutorial/collections/algorithms/index.html

  • 1

1 answer

21


What are the differences between them?

First of all it is important to understand that Collection is a term that may be ambiguous, as there are:

  • Collection (or collections in free translation): That would be any data structure in which objects are stored and can be iterated;
  • Collection (java.util.Collection): Which is an interface that has the subinterfaces Set, List and Queue; and
  • Collections (java.util.Collections): Which is a class with some static methods to be used with subclasses of Collection.

While Set, List and Queue in addition to being collections (or Collection, with lowercase "c") are also Collection'as they implement the interface java.util.Collection. The same does not happen with the Map, that although it can be considered a collection, it does not implement the interface java.util.Collection.

See below:

Diagrama UML com relações de herança de classes

The main differences among the above mentioned interfaces are:

  • List: List of things;
  • Set: List of things without repetition;
  • Map: the value-key list, the key being unique; and
  • Queue: Queue.

Each interface has classes that implement them. As there are many I will just put the comparative framework of each of them, I think that summarizes very well the functionality of each:

tabela com as classes

Meaning of:

  • Ordered (ordered): When a collection is ordered, it means that it is possible to iterate the collection elements in a specific and non-random order.
  • Sorted (classified): When a collection is classified, it means that the order of the elements of the collection is determined according to some rule, known as order of classification.

Source: SCJP Sun Certified Programmer for Java 6

What situations or cases should I use each of the different collections?

The situation depends on your need, looking at the differences listed above becomes very clear when one should choose one or another collection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.