"Understanding Java Collection" (i)--set frame collction, Map

Source: Internet
Author: User
Tags array length set set

This article mainly introduces the framework of the Java collection, so that we have an understanding of the overall framework of the Java collection. The collection interface, the map interface, and the three sub-interface Set,list,queue of the collection interface are described in detail.

  

Introduction to the Java Collection class:

Java collections can be broadly divided into set, List, queue, and map four systems, where set represents an unordered, non-repeatable collection; The List represents an ordered, repeating set, while map represents a collection of mappings, and Java 5 adds a queue system collection. Represents a queue collection implementation.
A Java collection is like a container that can "throw" multiple objects (which are actually references to objects, but are customarily called objects) into the container. With the addition of generics from Java 5, the Java collection remembers the data types of the objects in the container, making the encoding more concise and robust.

The differences between the Java collection and the array:

1. The array length is specified at initialization time, which means that only fixed length data can be saved. The collection can hold data with indeterminate amounts. You can also save data that has a mapping relationship (that is, associative arrays, key-value pairs Key-value).
2. An array element can be either a base type value or an object. Only objects can be saved in the collection (actually just the reference variable of the object), and the variables of the base data type are converted to the corresponding wrapper class in order to be placed in the collection class.

Inheritance relationships between Java collection classes:

The Java Collection class is primarily derived from two interfaces: Collection and map,collection and map are the root interfaces of the Java Collection framework.



In the figure, Arraylist,hashset,linkedlist,treeset is an implemented collection class that we will often be useful to.

The map implementation class is used to hold data that has a mapping relationship. Each data that the map saves is a Key-value pair, which consists of a key and value two values. The key in the map is not repeatable, and the key user identifies each item of data in the collection.


In the figure, Hashmap,treemap is a collection class that we often use.

Collection Interface: Introduction

The collection interface is the parent interface of the set,queue,list. There are several methods defined in the collection interface that can be implemented by its subclasses to enable data manipulation. Because the method is more, steal a lazy, directly to the JDK document content to move over.

Methods defined in the interface

You can see collection usage: adding elements, deleting elements, returning the number of collection collections, and emptying the collection.
The iterator () method is highlighted, and the return value of the method is iterator<e>.

Traversing a collection element using iterator

The iterator interface is often referred to as an iterator, which is the parent interface of the collection interface. But iterator is primarily used to iterate over the elements in the collection.
There are 2 main methods defined in the iterator interface:



The following procedure simply demonstrates the logic of getting elements one by one through the iterator object.

1  Public classIteratorexample {2      Public Static voidMain (string[] args) {3         //Create a collection, add elements4Collection<day> days =NewArraylist<day>();5          for(intI =0;i<10;i++){6Day Day =NewDay (i,i*60,i*3600);7 Days.add (day);8         }9         //gets the iterator for the days collectionTenIterator<day> Iterator =days.iterator (); One          while(Iterator.hasnext ()) {//determine if there is a next element ADay next = Iterator.next ();//Remove the element -             //iterate one after the other to get the element and follow it -             ..... the         } -     } -  - }

Note:When iterating over a collection element using iterator, iterator does not pass the collection element itself to the iteration variable, but instead passes the value of the collection element to the iteration variable (just as the parameter pass is the value pass, the base data type passes the value, the reference type passes only the object's reference variable), Therefore, modifying the value of an iteration variable has no effect on the collection element itself.
The following program demonstrates this:
1  Public classIteratorexample {2      Public Static voidMain (string[] args) {3List<string> list =arrays.aslist ("Java language", "C language", "the C + + language");4Iterator<string> Iterator =list.iterator ();5          while(Iterator.hasnext ()) {6String next = Iterator.next ();//The value of the collection element is passed to the iteration variable, and only the object reference is passed. Save only addresses that point to the memory space of the object7Next = "Modified";8 System.out.println (next);9             Ten         } One System.out.println (list); A     } -  - }

The output results are as follows:

Modified modified [Java language, C language, C + + language]

  

The following is a detailed description of the collection interface of the three sub-interface Set,list,queue.

Introduction to Set Sets

The set set is basically the same as the collection collection, and does not provide any additional methods. The set is actually collection, but behaves slightly differently (set does not allow repeating elements).
The set collection does not allow the same elements to be included, and if an attempt is made to add two identical elements to the same set set, the addition operation fails, and the Append () method returns False, and the new element is not added.

Introduction to the list collection

The list collection represents an ordered, repeatable collection of elements in which each element has its corresponding sequential index. The list collection allows you to use duplicate elements, which can be indexed to access the collection elements at the specified location. The list collection defaults to setting the index of elements in the order in which they are added, such as the first element to add an index of 0, and the second to add an element index of 1 ...
List as a sub-interface of the collection interface, you can use all the methods in the collection interface. And because list is an ordered set, the list collection adds some methods to manipulate the collection elements according to the index.

Methods defined in the interface
void Add (int index, Object Element): Inserts the specified element (optional action) at the specified position in the list. **boolean addall (int index, COLLECTION<? extends e> C): * * Inserts all elements from collection C into the list at the specified position index. Object Get (Index): Returns the element at the specified position in the list. int indexOf (Object o): Returns the index of the specified element that first appears in this list, or 1 if the list does not contain the element. int lastIndexOf (Object o): Returns the index of the last occurrence of the specified element in this list, or 1 if the list does not contain this element. **object Remove (int index): * * Removes the element from the specified position in the list. Object Set (int index, Object Element): Replaces the element at the specified position in the list with the specified element. **list sublist (int fromIndex, int toindex): * * Returns a subset of all the collection elements between the specified FromIndex (inclusive) and Toindex (not included) in the list. Object[] ToArray (): Returns an array (from the first element to the last element) that contains all the elements in the list in the appropriate order.

In addition, Java 8 adds the following two default methods for the list interface.

void ReplaceAll (Unaryoperator operator): Re-sets all elements of the list collection based on the calculation rules specified by operator. void sort (Comparator c): Sorts the elements of the list collection according to the Comparator parameter.

  

Introduction to the Queue collection

Queue users emulate the data structure of the queue, which usually refers to the "FIFO" (fifo,first-in-first-out) container. The head of the queue is the element that holds the longest in the queue, and the tail of the queue is the element that is kept in the queue for the shortest time. The new element inserts (offer) to the end of the queue, and the Access Element (poll) operation returns the element at the head of the queue. Typically, queues do not allow random access to elements in the queue.

Introduction to the method map collection defined in the interface

Map users save data with mappings, so the map collection holds two sets of numbers, one for the user to save the key in the map, and the other for the user to save the Value,key and value in the map as data of any reference type. The key of map does not allow repetition, that is, any two key of the same map object is always returned false by the Equals method.
As described, there is a one-way relationship between key and value, that is, a unique, deterministic value can always be found through the specified key. When the data is fetched from the map, the corresponding value can be taken out as long as the specified key is given.


The relationship between a map set and a set set, a list collection

1. Relationship to set set
If you put all the keys in the map together, they make up a set set (all the keys are not in order, the key is not duplicated with the key), and actually the map does contain a keyset () method, and the user returns a set of all the keys in the map.
2. Relationship to the list collection
If you put all of the values in the map together, they are very similar to a list: elements can be duplicated between elements, each element can be looked up according to the index, except that the index in the map no longer uses an integer value, but a different object as the index.

Methods defined in the interface

The map also includes an inner class entry, which encapsulates a key-value pair. The entry consists of three methods as follows:



The most typical usage of a map collection is to add and remove key-value pairs in pairs, and then to determine whether the map contains the specified key, whether it contains the specified value, or the keyset () method provided by the map to get a collection of all keys. The Foreach loop is then used to traverse all the keys of the map, and all of the value can be traversed by key. The following program code demonstrates some of the basic features of map:



1  Public classMaptest {2      Public Static voidMain (string[] args) {3Day Day1 =NewDay (1, 2, 3);4Day Day2 =NewDay (2, 3, 4);5map<string,day> map =NewHashmap<string,day>();6         //put Key-value in pairs7Map.put ("First", day1);8Map.put ("Second", day2);9         //determines whether the specified key is includedTenSystem.out.println (Map.containskey ("First")); One         //determines whether the specified value is included A System.out.println (Map.containsvalue (Day1)); -         //Looping through -         //1. Get the set set of all keys in the map theSet<string> KeySet =Map.keyset (); -         //2. Traversing with foreach -          for(String key:keyset) { -             //gets the specified value based on key + System.out.println (Map.get (key)); -         } +         //Remove the Key-value from the key by AMap.Remove ("First"); at System.out.println (map); -     } -  - }

Output Result:
Truetrueday [hour=2, minute=3, Second=4]day [Hour=1, minute=2, second=3]{second =day [hour=2, Minute=3, second=4]}

The above summary of the Java Collection framework, through this article can understand the Java collection in the wrong complex relationship, while mastering some basic concepts and methods of operation of the collection.
Subsequent articles will take a closer look at the specific implementation classes in the Java collection. If you are interested, you can watch the following content to learn more about the Java collection.

Understanding Java Collection (ii)--Set Set
Understanding Java Collection (iii)--collection List
Understanding Java Collection (iv)--collection Queue
Understanding Java Collection (v)--set Map
Understanding Java Collection (vi)--collection and deletion of the details of the change, performance and selection recommendations (to be updated)

Reprint Link: https://www.jianshu.com/p/589d58033841

"Understanding Java Collection" (i)--set frame collction, Map

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.