Introduction to Java's collection framework system and java framework system

Source: Internet
Author: User

Introduction to Java's collection framework system and java framework system
Functions of collection classes

  • A collection class is also called a container class. Like an array, it is used to store data. However, the array type is single, the length is fixed, and the restriction is large. The collection class can dynamically increase the length.
  • The elements stored in the set are all objects (reference addresses), so the set can store different data types. However, if you want to compare elements to sort the set, the types must be consistent.
  • Provides a unified query method for addition, deletion, modification, and query.
  • Supports generics to avoid data inconsistencies and conversion exceptions. It also encapsulates common data structures.
A Collection framework system consists of Collection, Map, and Iterator. The functions of each part are as follows. There are three collections in the Collection system: Set, List, and Queue.
  • Set: elements are unordered and repeatable.
  • List: elements are ordered and repeatable.
  • Queue: it encapsulates the queues in the data structure.
Map System
  • Map is used to save data with ing relationships, that is, key-value pairs ). The key of the Map set is unique, and the value can be repeated. Therefore, a value can correspond to multiple keys.
  • In addition to common classes, the Map system also includes Properties.
Iterator (Iterator)
  • The basic function is to traverse all elements in the set. Except for the List set, there is a unique iterator Listiterator, and other collection classes are the same.
  • Each collection class has an iterator (). You can call this method to obtain the iterator object.
  • If the List set uses an iterator, we recommend that you use ListIterator, which has more methods than the original iterator.
  • In addition to traversing the set elements using the iterator, you can also use the foreach () method that enhances for and java8. If it is a List set, the for loop can also be used.
The Collection interface method Collection is the parent interface of the Set, List, and Queue interfaces. The sub-classes of Set, List, and Queue can use the following methods.

 

Boolean add (E) _______________________________ add the specified Element boolean addAll (Collection c) _______________ add all elements in the specified set to this collectionboolean contains (Object o) _____________________ whether the Collection contains the specified Element boolean containsAll (Collection <?> C) ___________ does the set contain all the elements in the specified set boolean remove (Object o) ___________________ remove the specified Element boolean removeAll (Collection <?> C) _____________ remove all elements of the specified collection parameter void clear () _______________________________________ clear all elements of the Set boolean retainAll (Collection <?> C) _____________ keep the elements in the specified Collection parameter, which is the intersection of elements of the Two Sets boolean equals (Object o) ___________________ compare whether the collection is equal to the specified Object boolean isEmpty () ______________________________ determine whether the set is empty Iterator <E> iterator () _________________________ the Iterator that returns this collection, used to traverse the int hashCode () _________________________ return the hash code value of the Set int size () _____________________________________ return the number of elements in this collection Object [] toArray () _____________________________ return an array of objects containing all elements of this Collection <T> T [] toArray (T []) _________________________ returns an array containing all elements of the Collection. The array type is the same as that of the specified array.
Map Interface Method
Boolean containsKey (Object key) ____________ whether the ing contains the specified key value boolean containsValue (Object value) ____________ if one or more keys in the key value pair are specified, returns true Set <Map. entry <K, V> entrySet () _________________ returns the Set view of the ing relationships contained in the ing. Set <K> keySet () ________________________________ return the Set view of all keys in the ing. Collection <V> values () _____________________ returns a Collection V get (Object key) ______________________________ returns the value of the specified key ing. If no value exists, null V put (K key, V value) __________________________ is returned to put a key-value Pair (key-value) void putAll (Map <? Extends K ,? Extends V> m) ____ copies all Mappings of the specified ing to this ing. boolean isEmpty () ______________________________ if this ing does not contain the key-value ing relationship, returns true boolean equals (Object o) _______________________ to compare whether the specified Object is equal to this ing int size () _____________________________________. The number of key-value ing relationships in this ing int hashCode () _________________________________ return the hash value of this ing

Set, List, and Queue features and Instances

 

Set: the Set storage elements are unordered and repeatable. Set is implemented based on map. For details, see the source code of the Set implementation class. Most methods of the Set are similar to those of the Collection interface. Only TreeSet adds many new methods. Main Implementation classes:
  • HashSet: The elements are unordered. Because the underlying operations are completed by HashMap, there are no repeated values, but null can be saved.
  • LinkedHashSet: it is a sub-type of HashSet. It uses a linked list to maintain the order of elements, and the elements are sorted by the insertion order. There is no difference between other elements and HashSet.
  • TreeSet: sorts elements. All elements must implement the Comparator interface (common Java classes have been implemented). If you add a custom class as an element, you must set a sorting rule.
  • If different elements are added to the TreeSet, the elements cannot be compared. Therefore, the elements of the TreeSet are of the same type.
  • TreeSet adds many methods, including retrieving part of the elements at the beginning and end and traversing the elements in descending order.
A simple example of HashSet
HashSet hs = new HashSet (); hs. add ("A"); hs. add ("Xiaoxiang"); hs. add (2); hs. add (2); hs. add (new Date (); Iterator it = hs. iterator (); while (it. hasNext () {System. out. println (it. next ();} System. out. println ("number of elements:" + hs. size (); System. out. println ("Remove element:" + hs. remove ("A"); hs. clear (); // clear all elements System. out. println ("number of elements:" + hs. size ());

 

  • Example: HashSet is a typical implementation of the Set. In addition to the iterator, we can also use the enhanced for loop to obtain the Set elements. You can also convert a set into an array.

 

Simple Example of LinkedHashSet
LinkedHashSet hs = new LinkedHashSet (); hs. add ("A"); hs. add ("Xiaoxiang"); hs. add (2); hs. add (new Date (); // use for-each to traverse the element for (Object lhs: hs) {System. out. println (lhs );}
  • Example Description: The orders HashSet and HashSet are similar. The difference is that the classes are sorted by element insertion order. You can view the effect of traversal elements.
Simple Example of TreeSet
TreeSet ts = new TreeSet();ts.add(10);ts.add(10);ts.add(30);ts.add(-50);System.out.println(ts);
  • Instance Description: Use TreeSet to add multiple values, and the printed results are displayed in order. However, the TreeSet sorting rules are not sorted by insert order, but by implemented natural sorting. You can also customize sorting.
Simple Example of adding different types of elements to TreeSet
public class TreeSetTest {public static void main(String[] args) {TreeSet ts = new TreeSet();ts.add("A");ts.add("B");ts.add("C");System.out.println(ts.toString());ts.add(1);System.out.println(ts); //ClassCastException}}
  • Instance Description: when different types of elements are added to a TreeSet, the elements cannot be compared. Therefore, the TreeSet cannot guarantee the sorting status and causes an exception. If you use generics, you can avoid data inconsistency.
Simple example of how to add a TreeSet
TreeSet ts = new TreeSet (); ts. add (10); ts. add (20); ts. add (-50); System. out. println (ts); System. out. println ("--------------------"); Iterator it = ts. descendingIterator (); // descending iterator, from large to small while (it. hasNext () {System. out. print (it. next () + "") ;}// get> = minimum element of the given element System. out. println ("ceiling:" + ts. ceiling (18); System. out. println (ts. first (); // The first element System. out. println (ts. last (); // The last element System. out. println (ts. pollFirst (); // obtain the first element, and then remove the element System. out. println (ts. pollLast (); // obtain the final element and then remove it}
Features: the elements in the List set are ordered and repeatable. Each element has a corresponding index. By default, indexes are set in the order they are added. Main Implementation classes:
  • ArrayList: The underlying layer is a variable array. The default capacity is 10. You can specify the initial capacity. The main application is search and change.
  • Hidden list: the underlying layer is maintained by the linked list. Add and delete main applications
Unique List iterator: ListIterator
  • ListIterator extends Iterator, adding methods for forward iteration, adding elements, and modifying elements: hasPrevious (), previous (), add (), set ()
The List class is added based on the index:

All newly added methods are added, deleted, modified, and queried Based on the index.

List Method Role description

E add (int index, Object obj)

Add the specified element to the element corresponding to the specified index value.

E remove (int index)

Removes the element corresponding to the specified index value.

E set (int index, E element)

Replace the elements corresponding to the specified index value with the specified element.

E get (int index)

Returns the element of the specified index value.

Int indexOf (Object o)

Returns the index value of the specified Element in the set for the first time. If this element is not included,-1 is returned.

Int lastIndexOf (Object o)

Returns the index value of the last occurrence of the specified Element in the set. If this element is not included,-1 is returned.

ListIterator <E> listIterator ()

Returns the list iterator for this list element (in the appropriate order ).

ListIterator <E> listIterator (int index)

Returns the list iterator of the elements in the list (in the proper order), starting from the specified position.

List <E> subList (int fromIndex, int toIndex)

Returns the child set between the specified fromIndex (inclusive) and toIndex (excluded.

A simple example of ArrayList and rule list: the main differences between ArrayList and rule list are different in the underlying implementation method, but the method is similar. So here we only use ArrayList to demonstrate the index method.
ArrayList al = new ArrayList (15); // specify the initial length. The default value is 10al. add ("A"); al. add ("B"); al. add (10); al. add (20); System. out. println ("before removal:" + al); al. remove (1); // remove the System element corresponding to index value 1. out. println ("after removal:" + al); // obtain the corresponding element of index value 1 at this time, System. out. println ("Index 1 element:" + al. get (1); // Add the element al at index value 1. add (1, "add"); System. out. println ("use add () to add an element at Index 1:" + al); // modify the corresponding element of Index 1. set (1, "Use set ()"); System. out. println ("use set () to modify elements:" + al); System. out. println (al. indexOf ("use set ()"); // obtain the index value of the element "use set ()" for (int I = 0; I <al. size (); I ++) {System. out. println (I + "-->" + al. get (I ));}
Note the differences between add () and set () in the code above. add () adds elements to the specified index. The original data in the index is moved backward, which is equivalent to inserting elements. Set () is to modify the elements at the specified index and overwrite the elements. ListIterator: A simple example
ArrayList al = new ArrayList (15); al. add ("A"); al. add ("B"); al. add (10); al. add (20); System. out. println ("---- use ListIterator -----"); ListIterator lis = al. listIterator (); while (lis. hasNext () {System. out. println (lis. next ();} System. out. println ("-------- reverse iteration ---------"); while (lis. hasPrevious () {System. out. println (lis. previous ());}
Note: The premise of using hasPrevious () for reverse iteration is to use a Forward Iteration first, otherwise the elements cannot be iterated. The Queue collection encapsulates the data structures of stacks, queues, and double-end queues. The Queue collection class does not support random access elements.
  • Queue features: first-in-first-out (FLFO) containers.
  • Stack features: advanced post-output (FILO) containers.
  • Dual-end queue features: Stack and queue features allow you to delete and insert queue headers and tails.
Main Implementation classes:
  • ArrayDeque: An array-based dual-end queue.
  • PriorityQueue: uses natural sorting or custom sorting to sort elements, but the sorting is heap sorting. Null cannot be inserted.
  • Shortlist: implements the List, Queue, and Deque interfaces, which can both use indexes and simulate dual-end queues. The function is very powerful. Here we only want to know about it.
  • ArrayDeque and shard list can be used as dual-end Queues with FIFO and FILO features.
Common Methods for dual-end queues

Because Deque and Queue interfaces are implemented, there are many methods, but Frist in the method is used to operate the team head, and Last is the operation team end. We recommend that you use this method, which is simple and clear.

Boolean add (E) _____________________________ Insert the specified element to the end void addFirst (e) __________________________ Insert the specified element to the beginning void addLast (E e) ___________________________ Insert the specified element to the end boolean offer (E) ______________________ Insert the specified element to the end boolean offerFirst (e) _____________________ Insert the specified element to the end boolean offerLast (E) ______________________ Insert the specified element into the end of E getFirst () ____________________________ to obtain the first element, but do not remove E getLast ()________ _____________________ Get the last element, but do not remove E peekFirst () _______________________________ get the first element of the dual-end queue, but do not remove it. E peekLast () ________________________________ get the last element of the dual-end queue, but do not remove it. E pollFirst () _______________________________ obtain and remove the first element E pollLast () _________________________________________ obtain and remove the last element E removeFirst () _________________________ obtain and remove the first element E removeLast () __________________________________ get and remove the last element E pop () _____________________________________ simulate the stack to pop up an element, the stack void push (E) ______________________________ push the element into the stack, pressure stack boolean removeFirstOccurrence (Object o) _____ remove the first specified Element (when traversing the double-end queue from the header to the end) boolean removeLastOccurrence (Object o) ______ remove the last occurrence of the specified Element (when traversing the double-end queue from the header to the tail)
A simple example of ArrayDeque
ArrayDeque ad = new ArrayDeque (); ad. add ("A"); ad. add ("Yin"); ad. add ("yang"); ad. add (100); System. out. println (ad); // gets the first element and the end System. out. println ("Header element:" + ad. getFirst (); System. out. println ("team end element:" + ad. getLast (); // inserts an element into the end of the ad. offer ("add an offer to team end"); ad. add ("add to team end"); System. out. println (ad); // removes the element ad from the queue header. removeFirst (); // remove the last element of the queue, ad. removeLast (); System. out. println ("Removing team heads and team tails" + ad );
A simple example of PriorityQueue is a standard Queue (FIFO) that uses heap sorting. This means that when we print the PriorityQueue object directly, the results may not meet our requirements. Isn't it automatically sorted ?? The code example is as follows:
PriorityQueue<Integer> al = new PriorityQueue<>();al.add(18);al.add(30);al.add(-5);al.add(9);al.add(15);System.out.println(al.toString()); //[-5, 9, 18, 30, 15]
  • Instance Description: Because heap sorting only ensures that the first element, that is, the root node element, is the smallest element in the current priority queue. As long as the element changes, heap shuffling will occur, for example, offer () is used () add an element or poll () to obtain the Header element.
  • Solution: Use a for loop to traverse elements. Note: The for loop enhancement and iterator traversal elements both show unexpected results.
Int len = al. size (); // ensure that the number of traversal times is the original number of elements for (int I = 0; I <len; I ++) {System. out. print (al. poll () + ""); // This element is removed after an element is obtained .}


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.