Introduction to various types of Java containers

Source: Internet
Author: User

In programming, we almost always need to organize a group of the same kind of objects, such as a bunch of students or a group of workers, because of their number is not determined, we need a thing to help manage, this is used to manage the things commonly referred to as containers. We can add or delete objects dynamically through a container, traverse all or find an object, and so on.     The Java class Library provides us with a large number of commonly used container artifacts. The action of placing objects in a container is similar, and removing objects from the container is different, which is where each container differs. The container type can be broadly divided into the following two types: CollectionA sequence of independent elements that obey one or more rules. The list is the collection with the least restrictive, which saves the elements in the order in which they are inserted, but you can access all the elements arbitrarily. The queue follows the queuing rules to determine the order in which objects are produced (usually the same order in which they are inserted), and you can only take the elements that are sorted in front of them. Stacks are sorted in the advanced order, so you can only take the last element into the container.     Set cannot have duplicate elements. In the container we use, List seems to provide the same functionality that other containers implement, because the object is yours to take, so why should there be other containers? In fact, the organization of the object is inseparable from a variety of data structures, the structure behind each container is different, it will directly determine how you perform various operations, such as moving and removing elements. So, choosing a container is choosing the data structure behind it, which is how efficiently you choose to do some kind of operation. MapA pair of "key-value pairs" objects that allow you to use keys to look up values. ArrayList allows you to use numbers to find values, so in a sense it associates numbers with objects. The mapping table allows us to use another object to find an object, also known as an associative array, because it associates some objects with other objects, or "dictionaries," because you can use a key object to look up a value object, as defined by using a word in a dictionary. Map is a powerful programming tool.
ListThere are two types of lists:
    • Basic ArrayList: It is longer than the random-access element (although less used), but it is slower to insert and remove elements in the middle of the list. This is because it is implemented as an array at the bottom.
    • LinkedList: It is relatively slow in terms of random access, but can lower the cost of inserting and deleting elements in the middle of the list. This feature is due to the fact that the underlying data is organized using linked lists.
iterators InteratorWe often use the ability to traverse container objects for access, or delete, and so on, using iterators and polymorphism to traverse container objects without using the container's true type. An iterator is an object whose work is to traverse and select the objects in the sequence, and the client programmer does not have to know or care about the underlying structure of the sequence. In addition, iterators are often referred to as lightweight objects: the cost of creating it is small. Therefore, it is often possible to see some strange limitations on iterators; For example, Java's iterator can only be moved one way, and this iterator can only be used to:
    1. Using method iterator () requires the container to return a iterator. Iterator will be ready to return the first element of a sequence.
    2. Use Next () to get the next element in the sequence.
    3. Use Hasnext () to check if there are elements in the sequence.
    4. Use Remove () to delete the element that is newly returned by the iterator.
ListiteratorListiterator is a more powerful subtype of iterator that can only be used for access to a variety of list classes. Although the iterator can only move forward, Listiterator can move in both directions. It can also produce an index relative to the previous and subsequent elements of the current position that the iterator points to in the list, and you can use the set () method to replace the last element that it accesses. You can generate a listinterator that points to the beginning of the list by calling the Listiterator () method, and you can also call Listinterator (n) Method creates a listiterator at the beginning of an element that points to a list index of N.
Stack"Stack" is usually referred to as the "advanced post-out" container. Sometimes stacks are also called stack stacks, because the last "push-in" stack element, the first "pop-up" stack.     Often used to analogy the stack of things is a spring-loaded storage device in the buffet tray, the last loaded tray is always the first to take out the use. Because the list can simulate the behavior of a stack, the implementation of the Stack class uses a list.
Queue A queue is a typical first-in, in-out (FIFO) container. That is, the object is placed from one end of the container, removed from the other end, and the order in which the items are placed in the container is the same as the order taken.     Queuing is often used as a secure way to transfer objects from one area of a program to another, which is particularly important in concurrent programming. LinkedList provides a method to support the behavior of the queue, and it implements the queues interface, so linkedlist can be used as an implementation of the queue. By transforming the linkedlist upward into a queue. PriorityqueueFIFO describes the most typical queue rules. A queue rule is a rule that determines the elements of the next popup queue, given the elements in a set of queues.     FIFO declares that the next element should be the element with the longest wait time.     The priority queue declares that the next pop-up element is the most needed element (with the highest priority). When you use the offer () method to insert an element in the Priorityqueue, the object is sorted in the queue. The default sort will use the natural order of the objects in the queue, but you can modify this order by providing your own comparator.
SetSet does not save duplicate elements (as for how to determine the same element is more complex, you will see later). If you try to add multiple instances of the same object to the set, it will prevent this repetition. The most common use of set is test attribution, and it's easy to ask if an object is in a set.     Because of this, finding becomes the most important operation in set, so you usually choose an implementation of HashSet, which is optimized for quick find. The set has exactly the same interface as the collection, so there is no additional functionality, unlike the previous two different lists.     In fact set is collection, but behaves differently. If you use HashSet to output the set, you will find that the output is irregular, because HashSet uses hashing. TreeSet stores elements in a red-black tree data structure, so the output is ordered.     Linkedhashset also uses hashing because of the query speed, but it looks like it uses a linked list to maintain the order in which elements are inserted.     Objects must support comparability (comparable) when using TreeSet, which is also reflected in TreeMap. HashSet relies on hashcode (), Equals () to complete the judgment of repeating elements, which is also reflected in HashMap.
MapThe map provides access to the key-value pairs, which are similar to the set in the implementation, and are also available for hashmap,treemap,linkedhashmap use. Typically, if you do not sort the output, use HashMap.
foreach and iteratorsThe following shows the foreach application on the container. public class Foreachcollections {public static void main (string[] args) {collection<string> cs = new          Linkedlist<string> ();          Collection.addall (CS, "take the long-to-home". Split (")"); for (String S:cs) System.out.print ("'" + S + "'")}} because CS is a collection, this code shows that being able to work with foreach is all Co     The attributes of the Llection object. It works because Java introduces a new interface called Iterator, which contains a iterator () method capable of producing iterator, and the iterator interface is used by foreach to move through the sequence.     Therefore, if you create any class that implements iterator, you can use it in a foreach statement. In fact, the functionality provided by the foreach statement is a subset of the iterator's functionality, which, in addition to the reference, can be removed by the iterator, and foreach can only get the reference.

Introduction to various types of Java containers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.