Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Java collection frameworks?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the Java collection framework". In the daily operation, I believe that many people have doubts about the Java collection framework. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what is the Java collection framework?" Next, please follow the editor to study!

I. set frame diagram

Simplified diagram:

Description: for the above frame diagram, there are the following points

1. All collection classes are located under the java.util package. The collection class of Java is mainly derived from two interfaces: Collection and Map,Collection and Map are the root interfaces of the Java collection framework, which in turn contain some subinterfaces or implementation classes.

2. Collection interface: 6 interfaces (represented by short dashed lines), which represent different collection types, which is the basis of the collection framework.

3. Abstract class: 5 abstract classes (represented by long dotted lines), which partially implement the collection interface. Can be extended to a custom collection class.

4. Implementation class: 8 implementation classes (solid line representation), the concrete implementation of the interface.

5. The Collection interface is a set of objects that allow repetition.

6. The Set API inherits Collection and the collection elements are not duplicated.

7. The List API inherits Collection, allows repetition, and maintains the insertion order of elements.

8. The Map interface is a key-value object and has nothing to do with the Collection interface.

9. Set, List, and Map can be regarded as three categories of collections:

The List collection is an ordered collection, the elements in the collection can be repeated, and the elements in the access collection can be accessed according to the index of the element.

The Set collection is an unordered collection, the elements in the collection cannot be repeated, and the elements in the access collection can only be accessed according to the elements themselves (which is also the reason why the elements in the collection are not allowed to repeat).

Elements in the form of Key-value pairs are saved in the Map collection, and the value of each element can only be accessed based on its key.

II. Overall analysis

A general description:

Look at the frame diagram above and grab its backbone, namely Collection and Map.

1. Collection is an interface, a highly abstract collection, which contains the basic operations and properties of the collection. Collection includes two branches: List and Set.

List is an ordered queue, and each element has its index. The index value of the first element is 0. The implementation classes of List are LinkedList, ArrayList, Vector, Stack.

Set is a collection that does not allow duplicate elements. The implementation classes of Set are HastSet and TreeSet. HashSet depends on HashMap, which is actually implemented through HashMap; TreeSet depends on TreeMap, which is actually implemented through TreeMap.

2. Map is a mapping interface, that is, key-value key-value pairs. Each element in Map contains "one key" and "value corresponding to key". AbstractMap is an abstract class that implements most of the API in the Map interface. HashMap,TreeMap,WeakHashMap inherits from AbstractMap. Although Hashtable inherits from Dictionary, it implements the Map interface.

3. Next, take a look at Iterator. It is a tool for traversing collections, that is, we usually traverse collections through Iterator iterators. We say that Collection depends on Iterator because all the implementation classes of Collection implement the iterator () function and return an Iterator object. ListIterator exists specifically for traversing List.

4. Look at Enumeration, which is an abstract class introduced by JDK 1.0. Like Iterator, it also traverses collections; but Enumeration has less functionality than Iterator. In the block diagram above, Enumeration can only be used in Hashtable, Vector, and Stack.

Finally, look at Arrays and Collections. They are two utility classes that manipulate arrays and collections.

With the overall framework above, we then analyze each class separately.

III. Collection interface

The Collection interface is the root interface for dealing with a collection of objects, which defines a number of methods for manipulating elements. The Collection interface has two main subinterfaces, List and Set. Note that Map is not a subinterface of Collection. Keep this in mind.

The methods in the Collection interface are as follows:

Among them, there are several more common methods, such as the method add () to add an element to the collection, addAll () to add all the elements in the specified collection, the contains () method to detect whether the collection contains the specified elements, and the toArray () method to return an array representing the collection.

In addition, there is an iterator () function in Collection, which returns an Iterator interface. Typically, we iterate through the collection through the Iterator iterator. ListIterator is unique to the List interface, where a ListIterator object is returned through ListIterator () in the List interface.

The Collection interface has two commonly used subinterfaces, which are described in more detail below.

1.List interface

The List collection represents an ordered collection, and each element in the collection has its corresponding sequential index. The List collection allows repeating elements to be used, and the collection elements at a specified location can be accessed by index.

The List interface, which inherits from the Collection interface, defines an ordered collection that allows repetition. Because the elements in the List are ordered, we can access the elements in the List by using the index (the position of the element in List, similar to the array subscript), which is similar to the array of Java.

The List interface is the Collection direct interface. List stands for ordered Collection, that is, it maintains the order of elements in a specific insertion order. Users can precisely control the insertion position of each element in the list, access the element according to its integer index (position in the list), and search for elements in the list. The main collections that implement List interfaces are: ArrayList, LinkedList, Vector, Stack.

(1) ArrayList

ArrayList is a dynamic array and our most commonly used collection. It allows any element that conforms to the rules to be inserted, even including null. Each ArrayList has an initial capacity (10), which represents the size of the array. As the elements in the container increase, so does the size of the container. Each time an element is added to the container, a capacity check is performed, and when there is a quick overflow, a capacity expansion operation is carried out. Therefore, if we specify the number of elements to be inserted, it is best to specify an initial capacity value to avoid excessive expansion operations and waste of time and efficiency.

Size, isEmpty, get, set, iterator, and listIterator operations all run at a fixed time. The add operation runs at an allocated fixed time, that is, adding n elements takes O (n) time (since expansion is taken into account, this is not just as simple as adding elements to share the fixed time overhead).

ArrayList is good at random access. At the same time, ArrayList is asynchronous.

(2) LinkedList

LinkedList, which also implements the List interface, is different from ArrayList. ArrayList is a dynamic array, while LinkedList is a two-way linked list. So it not only has the basic operation method of ArrayList, but also provides the get,remove,insert method in the head or tail of LinkedList.

Due to the different ways of implementation, LinkedList cannot be accessed randomly, and all its operations are performed according to the needs of the double linked list. The operation of the index in the list traverses the list from the beginning or end (from one end near the specified index). The advantage of this is that inserts and deletions can be done in List at a lower cost.

Like ArrayList, LinkedList is asynchronous. If multiple threads access a List at the same time, you must implement access synchronization yourself. One solution is to construct a synchronous List when creating a List:

List list = Collections.synchronizedList (new LinkedList (...))

(3) Vector

Similar to ArrayList, but Vector is synchronous. So Vector is a thread-safe dynamic array. Its operation is almost the same as ArrayList.

(4) Stack

Stack inherits from Vector and implements a last-in, first-out stack. Stack provides five additional methods to enable Vector to be used as a stack. The basic push and pop methods, and the peek method to get the elements at the top of the stack, the empty method to test whether the stack is empty, and the search method to detect the position of an element in the stack. The Stack is empty after it has been created.

2.Set interface

Set is a Collection that does not include repeating elements. It maintains its own internal ordering, so random access doesn't make any sense. Like List, it also allows the existence of null, but only one. Because of the particularity of the Set interface, all elements passed into the Set collection must be different, and be aware of any mutable objects. If you operate on the elements in the collection, resulting in e1.equals (e2) = = true, some problems are bound to arise. There are three concrete implementation classes of Set interface, which are hash set HashSet, chain hash set LinkedHashSet and tree set TreeSet.

Set is a Collection that does not contain repeating elements, unordered, that is, any two elements E1 and e2 have e1.equals (e2) = false,Set with at most one null element.

It is important to note that although the elements in the Set are not in order, the position of the elements in the set is determined by the HashCode of the element, and its specific location is actually fixed.

In addition, it should be noted that there are special requirements for non-repetition in the set interface.

For example, object An and object B are originally two different objects. Normally, they can be put into Set, but if both objects An and B override the hashcode and equals methods, and the overridden hashcode and equals methods are the same. Then An and B cannot be put into the Set set at the same time, that is, the deduplication in the Set set is directly related to the hashcode and equals methods.

To better understand, take a look at the following example:

Public class Test {public static void main (String [] args) {Set set=new HashSet (); set.add ("Hello"); set.add ("world"); set.add ("Hello"); System.out.println ("the size of the collection is:" + set.size ()); System.out.println ("the elements in the collection are:" + set.toString ());}}

Running result:

The size of the collection is: 2

The elements in the collection are: [world, Hello]

Parsing: because the hashcode and equals methods are overridden in the String class, it is used to compare whether the string stored by the pointed string object is equal. So the second Hello here cannot be added.

Look at another example:

Public class TestSet {public static void main (String [] args) {Set books = new HashSet (); / / add a string object books.add (new String ("Struts2 authoritative Guide")); / / add a string object again, / / add a string object because the two string objects are equal through the equals method, so add failed and return false boolean result = books.add ("Struts2 authoritative Guide") System.out.println (result); / / the following output shows that the collection has only one element, System.out.println (books);}}

Running result:

False [authoritative Guide to Struts2]

Note: in the program, the string object added twice by the book collection is obviously not an object (the program uses the new keyword to create a string object), when using the = = operator to determine the return false, using the equals method to compare and return true, so can not be added to the Set collection, and finally can only output one element.

(1) HashSet

HashSet is a collection without repeating elements. It is implemented by HashMap and does not guarantee the order of elements (no order here means that the order of element insertion is inconsistent with the order of output), and HashSet allows the use of null elements. HashSet is asynchronous, and if multiple threads access a hash set at the same time, and at least one of them modifies the set, it must remain externally synchronized. HashSet stores the elements of the collection according to the Hash algorithm, so it has good access and lookup performance.

HashSet is implemented roughly as follows, using an HashMap to store elements, which are stored in the Key of HashMap, while Value uniformly uses an Object object.

Misunderstandings in the use and understanding of HashSet:

Null values are stored in a.HashSet. Null values are allowed in HashSet, but only one null value can be stored in HashSet.

The location of the storage elements in the b.HashSet is fixed. There is nothing to say about the unordered elements stored in HashSet, but because the underlying HashSet is implemented based on the Hash algorithm and uses hashcode, the location of the corresponding elements in HashSet is fixed.

c. Mutable objects (Mutable Object) must be handled carefully. If a variable element in a Set changes its state and causes Object.equals (Object) = true, it will cause some problems.

(2) LinkedHashSet

LinkedHashSet inherits from HashSet, and its underlying layer is based on LinkedHashMap, which is orderly and asynchronous. The LinkedHashSet collection also determines where elements are stored based on their hashCode values, but it also uses linked lists to maintain the order of elements. This makes it look as if the elements are saved in insertion order, that is, when traversing the collection, LinkedHashSet will access the elements of the collection in the order in which they were added.

(3) TreeSet

TreeSet is an ordered collection whose underlying implementation is based on TreeMap and is not thread-safe. TreeSet ensures that the collection elements are in a sorted state. TreeSet supports two sorting methods, natural sorting and custom sorting, in which natural sorting is the default sorting method. When we construct a TreeSet, if we use a constructor without arguments, the TreeSet uses a natural comparator; if you need to use a custom comparator, you need to use parameters with a comparator.

Note: the TreeSet collection does not compare elements through the hashcode and equals functions. It uses the compare or comparaeTo function to determine whether the elements are equal. The id function determines the id of two objects, and the same id is judged as a repeating element and will not be added to the collection.

IV. Map interface

Unlike List and Set interfaces, Map is a collection of key-value pairs that provide key-to-Value mapping. It also does not inherit Collection. In Map, it ensures the one-to-one correspondence between key and value. That is to say, a key corresponds to a value, so it cannot have the same key value, but of course the value can be the same.

1.HashMap

It is implemented in a hash table data structure. The location of an object is calculated by a hash function. It is designed for fast query. An array of hash tables (Entry [] table) is defined internally. The element converts the hash address of the element into the index stored in the array through the hash conversion function. If there is a conflict, all elements with the same hash address are strung together in the form of a hash list. Perhaps by looking at the source code of HashMap.Entry, it is a single linked list structure.

2.LinkedHashMap

LinkedHashMap, a subclass of HashMap, retains the order in which it is inserted, and if you need to output in the same order as you did at input, choose LinkedHashMap.

LinkedHashMap is a hash table and link list implementation of the Map interface with a predictable iteration sequence. This implementation provides all optional mapping operations and allows the use of null values and null keys. This class does not guarantee the order of the mapping, especially it does not guarantee that the order is permanent.

The LinkedHashMap implementation differs from HashMap in that the latter maintains a doubly linked list that runs on all entries. This link list defines the iteration order, which can be the insertion order or the access order.

According to the order of the elements in the linked list, it can be divided into: the linked list in the insertion order, and the linked list in the access order (calling the get method). The default is to sort by insertion order. If you specify to sort by access order, after calling the get method, the accessed elements will be moved to the end of the linked list, and continuous access can form a linked list sorted by access order.

Note that this implementation is not synchronous. If multiple threads access the hash mapping of a link at the same time, and at least one of them modifies the mapping structurally, it must maintain external synchronization. Because LinkedHashMap needs to maintain the insertion order of elements, its performance is slightly lower than that of HashMap, but it will have good performance when iterating to access all elements in Map, because it maintains the internal order in a linked list.

3.TreeMap

TreeMap is an ordered collection of key-value, asynchronous, based on the red-black tree (Red-Black tree) implementation, each key-value node as a node of the red-black tree. TreeMap will be sorted when it is stored, and key-value key-value pairs will be sorted according to key. There are also two sorting methods, one is natural sorting, the other is custom sorting, depending on the construction method used.

Natural sorting: all key in TreeMap must implement the Comparable interface, and all key should be objects of the same class, otherwise an ClassCastException exception will be reported.

Custom sorting: when defining TreeMap, create a comparator object that sorts all key values in all treeMap. Custom sorting does not require all key in TreeMap to implement the Comparable interface.

TreeMap's criterion for determining the equality of two elements: if two key returns 0 through the compareTo () method, the two key are considered to be equal.

If you use a custom class as the key value in TreeMap, and you want TreeMap to work well, you must override the equals () method in the custom class. The criterion for judging equality in TreeMap is that two key are returned as true through the equals () method, and a comparison by the compareTo () method should return 0.

5. Detailed explanation of Iterator and ListIterator

1.Iterator

Iterator is defined as follows:

Public interface Iterator {}

Iterator is an interface that is an iterator of a collection. The collection can traverse the elements in the collection through Iterator.

The API API provided by Iterator is as follows:

Boolean hasNext (): determines whether the next element exists in the collection. If so, the hasNext () method returns true.

Object next (): returns the next element in the collection.

Void remove (): deletes the element returned by the last next method in the collection.

Examples of use:

Public class IteratorExample {public static void main (String [] args) {ArrayList a = new ArrayList (); a.add ("aaa"); a.add ("bbb"); a.add ("ccc"); System.out.println ("Before iterate:" + a); Iterator it = a.iterator (); while (it.hasNext ()) {String t = it.next (); if ("bbb" .equals (t)) {it.remove () } System.out.println ("After iterate:" + a);}}

The output is as follows:

Before iterate: [aaa, bbb, ccc] After iterate: [aaa, ccc]

Note:

Iterator can only move in one direction.

Iterator.remove () is the only safe way to modify the collection during the iteration; changing the base collection in any other way during the iteration will result in unknown behavior. And each time the next () method is called, the remove () method can only be called once, and an exception will be thrown if this rule is violated.

2.ListIterator

ListIterator is a more powerful iterator that inherits from the Iterator interface and can only be used for access to various List types. You can generate a ListIterator that points to the beginning of the List by calling the listIterator () method, and you can call the listIterator (n) method to create a ListIterator that points to the element whose list index is n at the beginning.

The ListIterator API is defined as follows:

Public interface ListIterator extends Iterator {boolean hasNext (); E next (); boolean hasPrevious (); E previous (); int nextIndex (); int previousIndex (); void remove (); void set (E); void add (E e);}

From the above definition, we can deduce that ListIterator can:

Move in both directions (traversing forward / backward).

Generates an index of the previous and latter elements relative to the current position pointed to by the iterator in the list.

You can replace the last element it visited with the set () method.

You can use the add () method to insert an element before the element returned by the next () method or after the element returned by the previous () method.

Examples of use:

Public class ListIteratorExample {public static void main (String [] args) {ArrayList a = new ArrayList (); a.add ("aaa"); a.add ("bbb"); a.add ("ccc"); System.out.println ("Before iterate:" + a); ListIterator it = a.listIterator (); while (it.hasNext ()) {System.out.println (it.next () + "," + it.previousIndex () + "," + it.nextIndex () } while (it.hasPrevious ()) {System.out.print (it.previous () + ");} System.out.println (); it = a.listIterator (1); while (it.hasNext ()) {String t = it.next (); System.out.println (t); if (" ccc ".equals (t)) {it.set (" nnn ");} else {it.add (" kkk ") } System.out.println ("After iterate:" + a);}}

The output is as follows:

Before iterate: [aaa, bbb, ccc] aaa, 0, 1 bbb, 1, 2 ccc, 2, 3 ccc bbb aaa bbb ccc After iterate: [aaa, bbb, kkk, nnn]

VI. Similarities and differences

1.ArrayList and LinkedList

ArrayList implements the data structure based on dynamic array and LinkedList based on linked list.

Get and set,ArrayList are definitely better than LinkedList for random access, because LinkedList moves the pointer.

Add and remove,LinedList are more advantageous for adding and deleting operations, because ArrayList moves data.

It depends on the actual situation. If only a single piece of data is inserted or deleted, ArrayList is faster than LinkedList. But if the batch randomly inserts and deletes data, the speed of LinkedList is much better than that of ArrayList. Because every time ArrayList inserts a piece of data, it moves the insertion point and all data after it.

2.HashTable and HashMap

Similarities:

All implement the interfaces of Map, Cloneable and java.io.Serializable.

All of them are hash tables that store key-value pairs (key-value), and are all implemented by zipper method.

Differences:

(1) Historical reasons: HashTable is based on the stale Dictionary class, and HashMap is an implementation of the Map interface introduced by Java 1.2.

(2) synchronization: HashTable is thread-safe, that is to say, synchronous, while HashMap is not thread-safe, not synchronous.

(3) dealing with null values: both key and value of HashMap can be key of null,HashTable and value can not be null.

(4) the base class is different: HashMap inherits from AbstractMap, while Hashtable inherits from Dictionary.

Dictionary is an abstract class that inherits directly from the Object class and does not implement any interfaces. The Dictionary class was introduced with JDK 1.0. Although Dictionary also supports basic operations such as "add key-value key-value pair", "get value" and "get size", it has fewer API functions than Map; and Dictionary is generally traversed through Enumeration (enumeration class) and Map is traversed through Iterator (iterative M). However, because Hashtable also implements the Map interface, it supports both Enumeration traversal and Iterator traversal.

AbstractMap is an abstract class, which implements most of the API functions of the Map interface, and provides great convenience for the concrete implementation class of Map. It is a new class in JDK 1.2.

(5) different types of traversal are supported: HashMap only supports Iterator (iterator) traversal. Hashtable supports traversal in both Iterator (iterator) and Enumeration (enumerator).

Comparison of 3.HashMap, Hashtable, LinkedHashMap and TreeMap

Hashmap is the most commonly used Map, it stores data according to the HashCode value of the key, and its value can be obtained directly according to the key, so it has fast access speed. Over time, the order in which the data is obtained is completely random. HashMap only allows the key of one record to be Null;. The value of multiple records is that Null;HashMap does not support thread synchronization, that is, multiple threads can write HashMap; at the same time at any time, which may lead to data inconsistency. If you need synchronization, you can use Collections's synchronizedMap method to make HashMap have the ability to synchronize.

Hashtable is similar to HashMap, except that it does not allow recorded keys or values to be empty; it supports thread synchronization, that is, only one thread can write Hashtable at any one time, which also causes Hashtale to be slow to write.

LinkedHashMap saves the insertion order of records. When traversing LinkedHashMap with Iterator, the first records must be inserted first, or you can use parameters to sort them according to the number of applications. It will be slower than HashMap when traversing, but there is an exception. When the capacity of HashMap is very large and the actual data is less, it may be slower than LinkedHashMap, because the traversal speed of LinkedHashMap is only related to the actual data and has nothing to do with capacity, while the traversal speed of HashMap is related to its capacity.

If you need the output in the same order as the input, you can do it with LinkedHashMap, and it can be sorted in read order, as can be applied in connection pooling. The LinkedHashMap implementation differs from HashMap in that the latter maintains a double linked list that runs on all items. This link list defines the iteration order, which can be the insertion order or the access order. For LinkedHashMap, it inherits from HashMap, and the underlying layer uses a hash table and a two-way linked list to hold all elements. Its basic operation is similar to that of the parent class HashMap, which implements its linked list feature by overriding methods related to the parent class.

TreeMap implements the SortMap interface, and the internal implementation is a red-black tree. The records it saves can be sorted according to the key, and the default is the ascending order of the key value, or you can specify the sorting comparator. When you use Iterator to traverse the TreeMap, the resulting records are sorted. TreeMap does not allow the value of key to be null. Out of sync.

In general, what we use most is that the key-value pair stored in HashMap,HashMap is random when it is taken out, it stores data according to the HashCode value of the key, and its value can be obtained directly according to the key, with fast access speed. HashMap is the best choice for inserting, deleting, and locating elements in Map.

TreeMap fetches the sorted key-value pair. But TreeMap is better if you want to iterate through the keys in natural or custom order.

LinkedHashMap is a subclass of HashMap. If the output order is the same as the input, it can be implemented with LinkedHashMap, and it can also be arranged in read order, as can be applied in connection pooling.

Import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.TreeMap; public class MapTest {public static void main (String [] args) {/ / HashMap HashMap hashMap = new HashMap (); hashMap.put ("4", "d"); hashMap.put ("3", "c"); hashMap.put ("2", "b"); hashMap.put ("1", "a") Iterator iteratorHashMap = hashMap.keySet (). Iterator (); System.out.println ("HashMap-- >"); while (iteratorHashMap.hasNext ()) {Object key1 = iteratorHashMap.next (); System.out.println (key1 + "-" + hashMap.get (key1));} / / LinkedHashMap LinkedHashMap linkedHashMap = new LinkedHashMap (); linkedHashMap.put ("4", "d"); linkedHashMap.put ("3", "c"); linkedHashMap.put ("2", "b") LinkedHashMap.put ("1", "a"); Iterator iteratorLinkedHashMap = linkedHashMap.keySet (). Iterator (); System.out.println ("LinkedHashMap-- >"); while (iteratorLinkedHashMap.hasNext ()) {Object key2 = iteratorLinkedHashMap.next (); System.out.println (key2 + "-" + linkedHashMap.get (key2));} / / TreeMap TreeMap treeMap = new TreeMap (); treeMap.put ("4", "d"); treeMap.put ("3", "c") TreeMap.put ("2", "b"); treeMap.put ("1", "a"); Iterator iteratorTreeMap = treeMap.keySet (). Iterator (); System.out.println ("TreeMap-- >"); while (iteratorTreeMap.hasNext ()) {Object key3 = iteratorTreeMap.next (); System.out.println (key3 + "- -" + treeMap.get (key3));}

Output result:

HashMap-- > 3 Mui Mui c 2 Mui Mui b 1 Mui Mui a 4 Mui Mui d LinkedHashMap-- > 4 Mui Mui c 2 Muhami b 1 Mui a TreeMap-- > 1 Mui Mui a 2 Mui Mui b 3 Mui Mui c 4 Muir.

Comparison of 4.HashSet, LinkedHashSet and TreeSet

Set interface

Set is not allowed to contain the same elements, and if you try to add two identical elements to the same collection, the add method returns false.

Set determines that two objects are the same not by using the = = operator, but by the equals method. That is, as long as two objects are compared with the equals method and return true,Set, the two objects will not be accepted.

HashSet

HashSet has the following characteristics:

The order of elements cannot be guaranteed, and the order may change.

It's not synchronized.

The collection element can be a null, but only one null can be put in it.

When an element is stored in the HashSet union, HashSet calls the object's hashCode () method to get the hashCode value of the object, and then determines where the object is stored in the HashSet based on the hashCode value. To put it simply, the criterion for judging the equality of two elements by the HashSet set is that two objects are equal by the equals method, and the return value of the hashCode () method of the two objects is also equal.

Note that if you want to put an object in HashSet, override the equals method of the corresponding class for that object, and you should also override its hashCode () method. The rule is that if two objects return true through the equals method comparison, their hashCode should also be the same. In addition, the properties in the object that are used as equals comparison criteria should be used to calculate the value of hashCode.

LinkedHashSet

The LinkedHashSet collection also determines where elements are stored based on their hashCode values, but it also uses linked lists to maintain the order of elements. This makes it look as if the elements are saved in insertion order, that is, when traversing the collection, LinkedHashSet will access the elements of the collection in the order in which they were added.

LinkedHashSet performs better than HashSet when iterating to access all the elements in Set, but slightly worse than HashSet when inserting.

TreeSet class

TreeSet is the only implementation class for the SortedSet interface, and TreeSet ensures that collection elements are in a sorted state. TreeSet supports two sorting methods, natural sorting and custom sorting, in which natural sorting is the default sorting method. Objects of the same class should be added to the TreeSet.

The way TreeSet determines that two objects are not equal is that two objects return false through the equals method, or no 0 is returned by the CompareTo method comparison.

Natural ordering

Natural sorting uses the CompareTo (Object obj) method of the elements to sort to compare the size relationships between elements, and then sorts the elements in ascending order.

Java provides a Comparable interface, in which a compareTo (Object obj) method is defined, which returns an integer value, and the objects that implement the interface can be compared in size. If the obj1.compareTo (obj2) method returns 0, the two objects being compared are equal, if a positive number is returned, obj1 is greater than obj2, and if it is negative, obj1 is less than obj2. If we always return true from the equals method of the two objects, the compareTo method of the two objects should return 0.

Customized sorting

Natural sorting is sorted in ascending order according to the size of the collection elements. If you want to customize the sorting, you should use the Comparator interface to implement the int compare (T _ 1 ~ T _ 2) method.

Comparison of several set of package com.test; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.TreeSet; / * * @ description * HashSet: hash tables store information by using a mechanism called hashing, and elements are not stored in a particular order; * LinkedHashSet: maintains linked tables of collections in the order in which elements are inserted, allowing iterations in the order in which they are inserted * TreeSet: provides an implementation of using tree structure to store Set interface. Objects are stored in ascending order, and the access and traversal time is very fast. * @ author Zhou-Jingxian * / public class SetDemo {public static void main (String [] args) {HashSet hs = new HashSet (); hs.add ("B"); hs.add ("A"); hs.add ("D"); hs.add ("E"); hs.add ("C"); hs.add ("F"); System.out.println ("HashSet order:" + hs); LinkedHashSet lhs = new LinkedHashSet () Lhs.add ("B"); lhs.add ("A"); lhs.add ("D"); lhs.add ("E"); lhs.add ("C"); lhs.add ("F"); System.out.println ("LinkedHashSet order:" + lhs); TreeSet ts = new TreeSet (); ts.add ("B"); ts.add ("A"); ts.add ("D"); ts.add ("E") Ts.add ("C"); ts.add ("F"); System.out.println ("TreeSet order:" + ts);}}

Output result:

HashSet order: [d, E, F, A, B, C] LinkedHashSet order: [B, A, D, E, C, F] TreeSet order: [A, B, C, D, E, F]

5. The difference between Iterator and ListIterator

When we use List,Set, we often use Iterator (iterator) in order to traverse its data. With iterators, you don't need to interfere with the traversal process, you just need to take out the data you want one at a time and process it. But it is also different when using it.

Both List and Set have iterator () to get their iterators. For List, you can also get its iterator through listIterator (). The two iterators are not common in some cases. Iterator and ListIterator are mainly different in the following aspects:

ListIterator has an add () method, which can add objects to List, while Iterator cannot

Both ListIterator and Iterator have hasNext () and next () methods that enable sequential backward traversal, but ListIterator has hasPrevious () and previous () methods that implement reverse (sequential forward) traversal. Iterator can't.

ListIterator can locate the current index location, and nextIndex () and previousIndex () can implement it. Iterator does not have this feature.

You can delete objects, but ListIterator can modify objects, and the set () method can. Iierator can only be traversed and cannot be modified.

Because of these functions of ListIterator, the operation of List data structures such as LinkedList can be realized. In fact, array objects can also be implemented with iterators.

6. The difference between Collection and Collections

(1) java.util.Collection is a collection interface (a top-level interface of a collection class). It provides a general interface method to perform basic operations on collection objects. The Collection interface has many concrete implementations in the Java class library. The meaning of Collection interface is to provide a maximum unified operation mode for various specific collections, and its direct inheritance interfaces are List and Set.

HashSet order: [d, E, F, A, B, C] LinkedHashSet order: [B, A, D, E, C, F] TreeSet order: [A, B, C, D, E, F]

(2) java.util.Collections is a wrapper class (tool / helper class). It contains a variety of static polymorphic methods about collection operations. This class cannot be instantiated, just like a utility class for sorting, searching, thread-safe, and other operations on elements in the collection, serving Java's Collection framework.

Code example:

Import java.util.ArrayList; import java.util.Collections; import java.util.List; public class TestCollections {public static void main (String args []) {/ / Note that List is the List list = new ArrayList () that implements the Collection interface; double array [] = {112,111,23,456,231}; for (int I = 0; I < array.length; iTunes +) {list.add (new Double (array [I]));} Collections.sort (list) For (int I = 0; I < array.length; iTunes +) {System.out.println (list.get (I));} / result: 23.0 111.0 112.0 231.0 456.0} this is the end of the study on "what is the framework of Java collection", hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report