Java Collection Framework
gather
- Concept: an object's container, which defines common methods for operating multiple objects. Can implement the function of arrays.
- The difference between collection and array:
- The array length is fixed, the set length is not fixed
- Arrays can store primitive types and reference types, while collections can only store reference types.
test
/* 1. Add 2. Delete 3. Traversal 4. Judgment */ Collection col = new ArrayList(); ("Zhang San"); ("Li Si"); ("Wang Wu"); // ("Zhang San"); (col); // ("Zhang San");// (col); for (Object o : col) { (o); } ("------------------"); Iterator it = (); while (()){ String next = (String) (); (next); } (()); (("Zhang San"));
List interface
Features: Orderly, subscripted, and elements can be repeated.
You can add query elements at a specified position through the corner marker.
List list = new ArrayList(); ("java"); ("c++"); (1,"python"); (".net"); (()); (()); // each traversal ("---------------"); for (Object o : list) { (o); } //2. Iterator traversal ("---------------"); Iterator iterator = (); while (()){ (()); } //Iterator traversal ("-----------------"); ListIterator listIterator = (); while (()){ (()); } //Before reverse order, the forward order traversal must be performed, and the pointer points to the last element of the list before the traversal can be developed ("-------------------"); while (()){ (() + ":" +()); }
When adding basic data such as numbers, automatic boxing will be performed.
To delete a numeric element, you need to delete it through subscripts, or convert the numeric number that needs to be deleted into an object class or a wrapper class corresponding to this type.
subList
: Returns a subset with head and not tail.
List implementation class
ArrayList
- Array storage structure, fast query, slow addition and deletion;
- The JDK version 1.2 appears, with fast running efficiency and unsafe threads.
- Source code analysis:
- DEFAULT_CAPACITY = 10 Default Capacity . Note: If no elements are added to the collection, the capacity is 0, and after adding an element, the capacity is 10. Each expansion size is 1.5 times the original size. If the 11th element is added, the capacity changes from 10 to 15.
- add() method source code: Why after adding an element, the capacity is 10.
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! Increase the number of modifications elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = (DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - > 0) grow(minCapacity); } private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = ; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = (elementData, newCapacity); }
- elemetnData Array of storing elements
- size The actual number of elements
Test code:
ArrayList arrayList = new ArrayList(); Student s1 = new Student("Zhang San",18); Student s2 = new Student("Li Si",18); Student s3 = new Student("Wang Wu",18); (s1); (s2); (s3); (()); //Delete elements (need to override the equals method) (new Student("Li Si",18)); (()); public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != ()) return false; Student student = (Student) o; return age == && (name, ); }
Vector
- Array storage structure, fast query, slow addition and deletion;
- The JDK1.0 version appears, which is slow in operation and thread-safe;
- Enumerator traversal
Vector vector = new Vector(); ("java"); ("python"); (".net"); (()); //Enumeration tool traversal Enumeration elements = (); while (()){ (()); }
LinkedList:
- The two-way linked list storage structure is fast to add and delete, and the query is slow.
Generics:
- A new feature introduced in JDK1.5 is essentially a parameterized type, passing the type as a parameter;
- Common forms include generic classes, generic interfaces, and generic methods;
- benefit:
- Improve code reusability
- Prevent type conversion exceptions and improve code security
Generic Collections: Parameterized type and type-safe collection, and the types of the collection elements must be consistent.
Features:
- It can be checked at compile time, rather than throwing an exception at runtime.
- When accessing, there is no need to convert type.
- References between different generics cannot be assigned to each other, and generics do not have polymorphisms.
Set interface
Features: Unordered, no subscripts, elements that cannot be repeated
method: All methods inherited from Collection.
Set implementation class
HashSet
- Storage structure: hash table (array + linked list + red and black tree)
- Based on HashCode, elements are not repeated
- Calculate the saved location according to hashcode. If this location is empty, save it directly. If not empty, perform the next step.
- When the hash code of the stored element is the same, equals will be called for confirmation. If true, the latter deposit will be rejected. Otherwise, a linked list is generated.
public HashSet(){ map = new HashMap<>(); }
Test code:
HashSet<Student> set = new HashSet<>(); Student s1 = new Student("Zhang San",18); Student s2 = new Student("Li Si",18); Student s3 = new Student("Wang Wu",18); (s1); (s2); (s3); // (new Student("Li Si", 18)); (()); (()); // (new Student("Li Si", 18));// (()); // (()); for (Student student : set) { (student); } ("===================="); Iterator<Student> iterator = (); while (()){ (()); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != ()) return false; Student student = (Student) o; return age == && (name, ); } public int hashCode() { return (name, age); }
Reasons for adding 31 to the hashcode rewrite method
1.31 is a prime number that reduces hash collisions
2.31 Improve execution efficiency
TreeSet
- Storage structure:Red and black tree
- Implement elements without duplication based on arrangement order
- Implement the SortedSet interface to automatically sort collection elements
- The type of element object must implement the Comparable interface and specify the arrangement rules.
- Determine whether it is a duplicate element through CompareTo method
Test code: Use TreeSet collection to implement the sorting of strings by length
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { int n1 = () - (); int n2 = (o2); return n1==0?n2:n1; } ("zhangSan"); ("wkf"); ("asd"); ("abc"); ("ljCv"); ("liSi"); ("wanG"); (()); (());
Map interface
Features:
1. Used to store any key-value pair (Key, Value)
2. Key: Unordered, no subscript, no repetition allowed
3. Value: Unordered, no subscript, repetition allowed
Traversal:
- keySet() method traversal: get the set set of key.
- entrySet() method traversal: encapsulate map into an entry key-value pair collection.
Test code:
Map<String, String> map = new HashMap<>(); ("wkf","666"); ("qwe","678"); ("kfc","999"); ("asd","694"); Set<String> keySet = (); for (String s : keySet) { (s + "=" + (s)); } ("==================="); Set<<String, String>> entries = (); for (<String, String> entry : entries) { (() +"=" + () ); }
HashMap
- JDK1.2 version, threads are unsafe and run quickly; null is allowed as key or value.
- Construct an empty HashMap with default initial capacity 16 and default loading factor 0.75.
- Loading factor: For example, the current set capacity is 100, then when the data is stored at the 75th position, the capacity expansion operation is performed.
- Source code analysis
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // The initial capacity of hashMap is 16static final int MAXIMUM_CAPACITY = 1 << 30;//The maximum array capacity of hashMapstatic final float DEFAULT_LOAD_FACTOR = 0.75f;//Default loading factorstatic final int TREEIFY_THRESHOLD = 8;//Jdk1.8 starts, when the length of the linked list is greater than 8, it is adjusted to a red and black treestatic final int UNTREEIFY_THRESHOLD = 6;//Jdk1.8 starts, when the length of the linked list is less than 6, it is adjusted to the linked liststatic final int MIN_TREEIFY_CAPACITY = 64;//Jdk1.8 starts, when the length of the linked list is greater than 8 and the number of set elements is greater than or equal to 64, it is adjusted to a red and black tree.transient Node<K,V>[] table;//Arrays in hash table
Summarize:
- When HashMap was just created, the table is null. In order to save space, when adding the first element, the table capacity is adjusted to 16.
- When the number of elements is greater than the threshold (16*0.75=12), the capacity will be expanded, and the size after capacity expansion is twice the original size. The purpose is to reduce the number of adjustment elements
- Starting from jdk1.8, when the length of the linked list is greater than 8 and the number of set elements is greater than or equal to 64, the purpose is to improve execution efficiency
- Starting from jdk1.8, when the length of the linked list is less than 6, it is adjusted to the linked list.
- Before jdk1.8, the header is inserted in the linked list, and after jdk1.8, the tail is inserted.
Hashtable
- JDK1.0 version, thread-safe, slow running efficiency; null is not allowed as key or value
- Properties:
- A subclass of Hashtable requires that both key and value are Strings, which are usually used for reading configuration files.
TreeMap
- The SortedMap interface (a subinterface of Map) is implemented, and the keys can be automatically sorted.
Collections tool class
- sort(): Ascending order
- copy(): Copy
- binarySearch(): binary search
- (list, the value to be found);
- reverse(): reverse()
- shuffle(): disrupts elements in the collection
- Convert list into array:
- (new Integer[0]);
- Convert array into collection
- (names);
- A collection is a restricted collection that cannot be added and
Summarize
That’s all for this article. I hope it can help you and I hope you can pay more attention to more of my content!