JAVA learning notes-first understanding of the container class library, learning notes class library
I. Preface
In JAVA, everything is an object. Therefore, it is particularly important to hold objects.
In JAVA, we can create an object reference to hold the object:
HoldingObject holding;
You can also create an object array to hold a group of specific types of objects:
HoldingObject holding = new HoldingObject [10];
However, an object reference can only hold one object, and an object array can only hold a fixed number of objects of a specific type. However, we often encounter this situation when writing a program, we do not know how many objects to be created, or even the type of the objects to be created. Therefore, we need to be able to create any number of objects anywhere at any time, this is not what the above two methods can do. The JAVA utility Library provides a fairly complete Set of container classes to solve this problem. The basic types are List, Set, Queue, and Map, which are called "containers ".
Ii. container classification
As shown in, it is a simple container classification. We can see that there are actually only two types of containers, Collection and Map, and Collection can be divided into List, Set and Queue. Each of them has two or three implementations, for example, ArrayList, List, HashMap, and TreeMap. In the middle, common containers are represented by black rough wireframes; dotted wireframes represent interfaces; solid wireframes represent specific classes; and hollow arrows point-to-line represent a specific class to implement an interface; A solid arrow indicates that a class can generate the object pointed to by the arrow.
1) Collection:
Collection stores an Independent Sequence of elements that follow one or more rules. Collection is an interface that represents a group of objects. These objects are also called collection elements. Some collections allow repeated elements, while others do not. JDK does not provide any direct implementation of this interface. It provides more specific sub-interface implementation (List, Set, Queue). This interface is often used to pass collection, and operate these collections wherever they are most universal. The following describes some methods of Collection (from J2SE6_API ):
A) List: Elements must be saved in the inserted order.
List is an ordered collection. Users of this interface can precisely control the insert position of each element in the List. Users can access the element based on the integer index (position in the List) of the element, and search for the elements in the list. The List interface adds a large number of methods on the basis of the Collection, so that you can insert and remove elements in the middle of the List. A List allows you to add, remove, or resize an element after it is created, which is the value of the List:A modifiable Sequence. There are two types of List Implementation:
ArrayList: Random Element access is faster, but insertion and removal are slower;
ArrayList has three constructor methods:
ArrayList (); // construct an empty list ArrayList (int x) with an initial capacity of 10; // construct an empty list ArrayList (Collection <? Extends E> c); // construct a list of elements that contain the specified collection. These elements are arranged in the order returned by the collection iterator.
The following is a simple example to introduce the basic operations of ArrayList:
Package com. tongye. holding; import java. util. arrayList; import java. util. list; import java. util. random; public class HoldObject {public static void main (String [] args) {Random rand = new Random (47); Circle circle = new Circle (); square square = new Square (); Triangle triangle = new Triangle (); Rectangle rectangle = new Rectangle (); // create a List instance List <Integer> list1 = new ArrayList <Integer> (); // create a List that can only store int type objects <Shape> list2 = new ArrayList <Shape> (); // create a List that can only store Shape objects list3 = new ArrayList (4); // create a List with an initial capacity of 4, no storage type specified // Add the element for (int I = 0; I <10; I ++) list1.add (rand. nextInt (20); // add (E) method to add the specified element to the end of the list for (Integer I: list1) // All collections can be traversed using foreach. out. print (I + ""); System. out. println (""); // use the subList method to extract a part of the list1 View List <Integer> list4 = list1.subList (3, 8); // subList (int fromIndex, int toIndex ), return to the list // part of the view from fromIndex (included) to toIndex (not included) for (Integer I: list4) System. out. print (I + ""); System. out. println (""); // Add the list2.add (circle) element to list2; // Add the list2.add (square) object to the list; list2.add (triangle); list2.add (1, rectangle); // add (int index, E e) method, insert the specified Element for (Shape I: list2) to the specified position in the list) // All collections can be traversed using foreach. out. println (I); System. out. println (list2.isEmpty (); // The isEmpty () method. check whether any element exists in the list. If no element exists, true System is returned. out. println (list2.contains (circle); // The contains () method is used to check whether the list contains the specified element. If yes, true System is returned. out. println (list2.indexOf (square); // indexOf () method, used to return the index number list2.get (1) of the element in the list ). showShape (); list2.remove (rectangle); // remove (Object o) method to delete the specified list2.get (1) element that appears for the first time in the list ). showShape (); list2.remove (1); list2.get (1 ). showShape (); // remove (int index) method to delete the elements in the specified index in the list // Add the list3.add (100) element to list3 ); list3.add ("adding a string to the List"); list3.add (rectangle); list3.add (1.048596); list3.add ("automatic capacity growth"); for (int I = 0; I <5; I ++) System. out. println (list3.get (I) ;}} class Shape {public void showShape () {System. out. println ("Shape class") ;}} class Circle extends Shape {public void showShape () {System. out. println ("Circle class") ;}} class Square extends Shape {public void showShape () {System. out. println ("Square class") ;}} class Triangle extends Shape {public void showShape () {System. out. println ("Triangle class") ;}} class Rectangle extends Shape {public void showShape () {System. out. println ("Rectangle class ");}}ArrayList Code
Shortlist: Provides optimized sequential access through low-cost insert and delete operations in the middle of the List. The listlist interface also implements the basic List interface like ArrayList, but it is more efficient (insert and delete in List) When performing some operations than ArrayList ), however, random access operations are inferior. If we need to use the external List, we only need to modify the implementation of the List in the program, which is also the benefit of using the interface:
List <Integer> list = new partition List <Integer> (); // use the partition List to implement the list
B) Set: Duplicate elements are not allowed.
Set is a collection that does not contain repeated elements. More specifically, Set does not contain e1 and e2 elements that meet e1.equals (e2), and contains at most one null element; set has the same interface as Collection, so there is no additional function,Set is actually a Collection, but the behavior is different;It has three implementations: HashSet, TreeSet, and LinkedHashSet.
①. HashSet:
HashSet is a set implementation based on HashMap. It does not guarantee the iteration sequence of the set, especially it does not guarantee that the sequence remains unchanged permanently;
HashSet allows the use of null elements;
HashSet provides stable performance (add, remove, contains, size) for basic operations );
The time required for the HashSet iteration is proportional to the size (number of elements) of the HashSet instance and the "capacity" of the underlying HashMap instance. Therefore, if the iteration performance is very important, do not set the initial capacity too high (or set the loading factor too low );
HashSet is not synchronized. when accessing a HashSet in multiple threads at the same time, you need to use the synchronization statement to lock it. You can use Collection. the synchronizedSet method is used to wrap the set. It is best to complete this step when creating the set. Unexpected non-synchronous access to the Set: set s = Collections. synchronizedSet (new HashSet ());
The iterator returned by the iterator method of HashSet fails quickly: after creating the iterator, If you modify the set, unless you use the iterator's own remove method, otherwise, Iteractor throws an exception at any time and in any way.
HashSet has four constructor methods:
HashSet (); // create an empty set. The default initial capacity of the underlying HashMap instance is 16, and the load factor is 0.75 HashSet (Collection <? Extends E> c); // create a new setHashSet (int intialCapacity) that contains elements in the specified collection ); // create a setHashSet (int intialCapacity, float loadFactor) with the specified initial capacity and default load factor; // create a set with the specified initial capacity and load factor
② TreeSet:
TreeSet is a set implementation based on TreeMap;
TreeSet provides guaranteed time overhead (add, remove, contains) for basic operations );
TreeSet uses the natural sequence of elements to sort the elements, or sorts the elements based on the Comparator provided when the elements are created, depending on the construction method used;
TreeSet is not synchronized;
The iterator returned by the iterator method of the TreeSet fails quickly;
TreeSet has four constructor methods:
TreeSet (); // create a new empty set, which sorts the TreeSet (Collection <? Extends E> c); // creates a new TreeSet that contains the specified collection element. It sorts the TreeSet (Compartor <? Super E> compartor); // create a new empty TreeSet, which sorts the TreeSet (SortedSet <E> s) according to the specified comparator ); // create a new TreeSet with the same ing and same sorting as the specified Ordered set
③ LinkedHashSet:
LinkedHashSet is a hash table and Link List Implementation of the set interface with predictable iteration sequence;
LinkedHashSet defines the iteration sequence, that is, the iteration is performed based on the sequence in which elements are inserted to the set. The insertion sequence is not affected by the re-inserted elements in the set;
The time required for the LinkedHashSet iteration is proportional to the set size and has nothing to do with the capacity;
LinkedHashSet provides all optional set operations and allows null elements. It can provide stable performance for basic operations, non-synchronization, and fast failure of the iterator.
Its construction method is similar to HashSet.
The following is a simple example to introduce the basic operations of Set:
package com.tongye.holding;import java.util.Random;import java.util.Set;import java.util.HashSet;import java.util.TreeSet;public class SetExample { public static void main(String[] args){ Random rand = new Random(47); Set<Integer> hashSetInt = new HashSet<Integer>(); for(int i = 0;i < 100;i++) hashSetInt.add(rand.nextInt(20)); System.out.println(hashSetInt); Set<Integer> treeSetInt = new TreeSet<Integer>(); for(int i = 0;i < 100;i++) treeSetInt.add(rand.nextInt(20)); System.out.println(treeSetInt); }}Set Code
Note: In fact, when I run the above Code on eclipse, I found that the output elements of HashSet and TreeSet are arranged in a natural order. After reading the information, I found that this may be the reason for the JDK version, the implementation of HashMap in JDK 8 has changed. These new features lead to the arrangement of HashSet input integer data in the natural order.
C) Queue: Determine the order in which objects are generated based on queuing rules (usually the same as the order in which they are inserted)
Queue is a typical first-in-first-out container. It has two implementations: Queue list and PriorityQueue. The Queue list provides methods to support Queue behavior and implements the Queue interface. PriorityQueue (priority Queue) declares that the next pop-up element is the most required element (with the highest priority ).
2) Map:Stores a key-Value Pair object that is composed of a pair. You can use the key to find the value.
Map can be used to Map an object to other objects. The Map interface provides three collection views, allowing you to view a ing relationship in the form of a key set, value set, or key-value ing link set. The ing order is the order in which the iterator returns its elements on the collection ing collection view. It has two implementations: HashMap and TreeMap.
HashMap:
Based on the Map implementation of the hash table, this implementation provides all the optional ing operations, and allows the use of null values and the null key; The ing sequence is not guaranteed, especially the sequence is not always unchanged.
Constructor:
HashMap (); // create an empty HashMapHashMap (int initialCapacity) with the default initial capacity (16) and default load factor (0.75 ); // create an empty HashMapHashMap (int initialCapacity, float loadFactor) with the specified initial capacity and default loading factor ); // create a HashMapHashMap (Map <? Extends K ,? Extends V> m); // create a new HashMap with the same ing as the specified Map
TreeMap:
Based on the Map implementation of the Red/black tree, the ing is sorted based on the natural sequence of its keys, or based on the Compartor provided when the ing is created, depending on the construction method used.
TreeMap (); // create a new empty tree ing TreeMap (Compartor <? Super K> compartor); // constructs a new empty tree ing, which sorts the TreeMap (Map <? Extends K ,? Extends V> m); // constructs a new tree ing with the same ing relationship as the given ing. The soring sorts the TreeMap (SortedMap <K ,? Extends V> m); // constructs a new tree ing that has the same ing relationship and the same sorting order as the specified ordered ing.
The following uses a simple example to briefly introduce some Map usage:
Package com. tongye. holding; import java. util. hashMap; import java. util. map; import java. util. random; public class MapExample {public static void main (String [] args) {Random rand = new Random (47); Map <Integer, Integer> mapInt = new HashMap <Integer, integer> (); // create an empty New HashMap for (int I = 0; I <10000; I ++) {Integer key = rand. nextInt (20); Integer value = mapInt. get (key); // returns the value mapped to the key. If the key does not have any mappings Null mapInt. put (key, value = null? 1: value + 1); // associate the specified value with the specified key in this ing} System. out. println (mapInt );}}Map Code