1. Knowledge point architecture of collection
1) , knowledge structure system diagram
2) , collection overview
3) . architecture
4) , tools
5) , Description: the bottom structure here is a little bit, and there are special chapters in the later period
2. Overview of collection
1) , notes
/* *1. Overview of set *> the concept of sets *Collection and array are structures for storing multiple data, which are called Java containers for short *> note: current storage mainly refers to memory level storage, not to persistent storage *> array features review *Once initialized, its len gt h is determined and cannot be modified *Once an array is defined, the type of its elements is determined. We can only operate on data of the specified type *> the methods provided in the array are very limited, which are inconvenient and inefficient for adding, deleting, inserting data and other operations *> the requirement to get the number of actual elements in the array. There is no ready-made attribute or method available in the array *> characteristics of array data storage: orderly and repeatable. For disordered and unrepeatable needs, they cannot be satisfied *> general framework of collection framework * |-----Iterator ** ------- Collection interface: single column Collection, used to store one object *------- List interface: store orderly and repeatable data. -->Dynamic array * |------ArrayList,LinkedList,Vector *------- Set interface: store unordered and unrepeatable data * |-----HashSet,LinkedHashSet,TreeSet * *------ Map interface: a two column set used to store a pair of key value data * |-----HashMap,LinkedHashMap,TreeMap,Hashtable,Properties * * |-----Collections * */
3. Architecture
1) , iterator (iteration)
① , notes
/* *1. Itertor (iterator) *Concept: Iterator is an object whose job is to traverse and select the objects in the sequence. It provides a way to access the elements in the container object without exposing the internal details of the object *> note: iterator is a design pattern. It is an object. It can traverse and select the objects in the sequence, but developers do not need to understand the underlying structure of the sequence (iterator extracts access logic from different types of collection classes, so as to avoid exposing the internal structure of the collection externally) *> internal methods: hasNext() and next() *> the collection object gets a new iterator object every time it calls the iterator() method. The default cursor is before the first element of the collection *> remove() is defined internally to delete the elements in the collection when traversing. This method is different from the collection direct call remove() * */
② , code
public class ItertorTest01 { //Iterator is used to traverse a collection @Test public void demo01(){ Collection coll= new ArrayList(); //add(): adds an element coll.add(123); coll.add(798); coll.add("aa"); coll.add("AA"); coll.add("CC"); Iterator iterator = coll.iterator(); //hasNext(): determine whether there is another element while(iterator.hasNext()){ //next(): the pointer moves down, and then the element at the collection position returns System.out.println(iterator.next()); } } }
2) , collection interface
① , Description: the method of the collection interface is written directly in the test code, so you don't need to take notes alone
② , code
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import org.junit.Test; /* * 2.collection Interface * * */ public class CollectionTest02 { //Method test of collection interface @Test public void demo01(){ Collection coll=new ArrayList(); //add(Object e): add element e to the collection coll coll.add(456);//Automatic packing coll.add("XX"); coll.add(741); coll.add(new Date()); //size(): get the number of added elements System.out.println("Number of sets:"+coll.size()); //addAll(Collection coll1): add elements from the coll1 collection to the current collection Collection coll1=new ArrayList(); coll1.add(789); coll1.add("qwer"); coll1.addAll(coll);//Add elements from coll1 set to coll System.out.println("Number of sets:"+coll.size()); //clear(): empty set elements coll1.clear(); //isEmpty(): judge whether the current set is empty System.out.println(coll1.isEmpty()); System.out.println("----------------------------------------------"); Collection coll3= new ArrayList(); coll3.add(123); coll3.add("qq"); coll3.add(new Person("AA",18));//You can also add objects directly to a collection //contains(Object obj): to determine whether obj is included in the current collection, we will call equals() of the class of obj object boolean contains = coll3.contains("qq"); System.out.println(contains); Iterator iterator = coll3.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } //containsAll(Collection coll1): determines whether all elements in parameter coll1 exist in the current collection Collection coll4 = Arrays.asList(123,4567); System.out.println(coll3.containsAll(coll4)); } @Test public void demo02(){ Collection coll3= new ArrayList(); coll3.add(123); coll3.add("qq"); coll3.add(new Person("AA",18)); //remove(Object obj): removes the obj element from the current collection. coll3.remove("qq"); System.out.println(coll3); //removeAll(Collection coll3): subtraction, which removes all elements in coll3 from the current collection Collection coll4 = Arrays.asList(123,4567); coll3.removeAll(coll4); System.out.println(coll4); } @Test public void test3(){ Collection coll = new ArrayList(); coll.add(123); coll.add(456); coll.add(new Person("Jerry",20)); coll.add(new String("Tom")); coll.add(false); //5. Retain all (collection coll1): intersection: get the intersection of the current collection and coll1 collection and return it to the current collection //Collection coll1 = Arrays.asList(123,456,789); //coll.retainAll(coll1); //System.out.println(coll); //6.equals(Object obj): to return true, you need to have the same elements in the current set and parameter set. Collection coll1 = new ArrayList(); coll1.add(456); coll1.add(123); coll1.add(new Person("Jerry",20)); coll1.add(new String("Tom")); coll1.add(false); System.out.println(coll.equals(coll1)); } @Test public void test4(){ Collection coll = new ArrayList(); coll.add(123); coll.add(456); coll.add(new Person("Jerry",20)); coll.add(new String("Tom")); coll.add(false); //hashCode(): returns the hash value of the current object System.out.println(coll.hashCode()); //Set to array: toArray() Object[] arr = coll.toArray(); for(int i = 0;i < arr.length;i++){ System.out.println(arr[i]); } //Array to collection: call the static method asList() of the Arrays class List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"}); System.out.println(list); List arr1 = Arrays.asList(new int[]{123, 456}); System.out.println(arr1.size()); List arr2 = Arrays.asList(new Integer[]{123, 456}); System.out.println(arr2.size()); } } class Person{ String name; int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person() { super(); } }
3) , List interface
① , notes
/* *3.List interface *> list interface: store orderly and repeatable data *ArrayList: as the main implementation class of List interface, the thread is unsafe and efficient, and the underlying layer uses Object[] elementData storage *LinkedList: for frequent insert and delete operations, this kind of efficiency is higher than ArrayList; the underlying layer uses bidirectional linked list storage *> vector: as an old implementation class of List interface; thread safe and inefficient; the underlying uses Object[] elementData storage *Simple analysis of ArrayList source code *> JDK7 *> ArrayList list = new arraylist(); / / when instantiating, the underlying layer will create an Object [] array elementData with a length of 10 to store the elements * > list.add (123); / / elementData [0] = new integer (123); / / if this addition causes the capacity of the underlying elementData array to be insufficient, the capacity will be expanded. By default, the capacity will be expanded to 1.5 times the original capacity, and the data in the original array will need to be copied to the new array, *This will lead to capacity expansion and assignment, and reduce efficiency. It is recommended to use the constructor with parameters in development: ArrayList list = new ArrayList(int capacity) *> jdk8 *> ArrayList list = new arraylist(); / / when instantiating, the underlying Object[] elementData is initialized to {}. No array with length of 10 is created * > list.add (123); / / when add() is called for the first time, the underlying layer creates an array of length 10 and adds data 123 to elementData[0]. Subsequent addition and expansion operations are no different from JDK7 *The creation of ArrayList objects in JDK7 is similar to that of a single instance, while the creation of ArrayList objects in jdk8 is similar to that of a single instance, which delays the creation of arrays and saves memory *Simple analysis of LinkedList source code *> LinkedList list = new linkedlist(); the first and last attributes of Node type are declared internally, and the default value is null * > list.add (123); / / encapsulate 123 into Node and create Node object *> among them, Node is defined as: it represents the two-way linked list of LinkedList * private static class Node<E> { * E item; * Node<E> next; * Node<E> prev; * * Node(Node<E> prev, E element, Node<E> next) { * this.item = element; * this.next = next; * this.prev = prev; * } * } *Source code analysis of vector: when creating objects through Vector() constructor in jdk7 and jdk8, arrays with length of 10 are created in the bottom layer. In terms of capacity expansion, the default capacity expansion is twice the length of the original array *> comparison of ArrayList, LinkedList and Vector *> all three classes implement the List interface, which has the same characteristics of storing data: storing orderly and repeatable data *> different: see above *> common methods *void add(int index, Object ele): insert the ele element in the index position *boolean addAll(int index, Collection eles): add all elements in eles from the index position *Object get(int index): get the element at the specified index location *int indexOf(Object obj): returns the location where obj first appears in the collection *int lastIndexOf(Object obj): returns the last position of obj in the current set *Object remove(int index): removes the element at the specified index location and returns this element *Object set(int index, Object ele): set the element of the specified index position to ele *List subList(int fromIndex, int toIndex): returns the subset from fromIndex to toIndex *Add: add(Object obj) *Delete: remove(int index) / remove(Object obj) *Change: set(int index, Object ele) *Query: get(int index) *add(int index, Object ele) *Length: size() * * */
② , code
public class List03 { @Test public void test1(){ ArrayList list = new ArrayList(); list.add(123); list.add(456); list.add("AA"); list.add(new Person("Tom",12)); list.add(456); System.out.println(list); //void add(int index, Object ele): insert the ele element in the index position list.add(1,"BB"); System.out.println(list); //boolean addAll(int index, Collection eles): add all elements in eles from the index position List list1 = Arrays.asList(1, 2, 3); list.addAll(list1); //list.add(list1); System.out.println(list.size());//9 //Object get(int index): get the element at the specified index location System.out.println(list.get(0)); } @Test public void test2(){ ArrayList list = new ArrayList(); list.add(123); list.add(456); list.add("AA"); list.add(new Person("Tom",12)); list.add(456); //int indexOf(Object obj): returns the location where obj first appears in the collection. If not, return - 1 int index = list.indexOf(4567); System.out.println(index); //int lastIndexOf(Object obj): returns the last location of obj in the current collection. If not, return - 1 System.out.println(list.lastIndexOf(456)); //Object remove(int index): removes the element at the specified index location and returns this element Object obj = list.remove(0); System.out.println(obj); System.out.println(list); //Object set(int index, Object ele): set the element of the specified index position to ele list.set(1,"CC"); System.out.println(list); //List subList(int fromIndex, int toIndex): returns a subset of left closed and right open intervals from fromIndex to toIndex List subList = list.subList(2, 4); System.out.println(subList); System.out.println(list); } }
4) , Set interface
① , notes
/* *4.Set interface *> set interface: store unordered and unrepeatable data *> HashSet: as the main implementation class of Set interface; thread is unsafe; null value can be stored *LinkedHashSet: as a subclass of HashSet, when traversing its internal data, it can be traversed in the order of adding. For frequent traversal operations, LinkedHashSet is more efficient than HashSet *TreeSet: you can sort by the specified attribute of the added object *There is no additional method defined in the > set interface. All methods declared in the Collection are used *The storage of > set is disordered and non repeatable data, which is described by HashSet *> disorder: not equal to randomness. The data stored in the underlying array is not added in the order of array index, but determined by the hash value of the data *> non repeatability: ensure that when the added element is judged according to equals(), it cannot return true. That is, only one element can be added for the same element *The process of adding elements: take HashSet as an example *> we add element a to the HashSet. First, we call the hashCode() method of the class where element a is located to calculate the hash value of element A. then, we use some algorithm to calculate the storage location (i.e. index location) in the array at the bottom of the HashSet to determine whether there are elements in the array at this location *> if there are no other elements in this location, element a is added successfully *> if the hash value is the same, then you need to call the equals() method of the class of element a *> equals() returns true, failed to add element a *> equals() returns false, element a is added successfully *> for case 2 and case 3 where the addition is successful: element a and the existing data on the specified index location are stored as linked lists *> JDK7: put element a in the array and point to the original element *> jdk8: the original element is in the array, pointing to element a *The lower level of > set corresponds to the lower level of Map *> data added to TreeSet requires objects of the same class *> two sorting methods: natural sorting (implementing the compatible interface) and customized sorting (Comparator) *In natural sorting, the standard for comparing whether two objects are the same is: compareTo() returns 0. It is no longer equals() *In custom sorting, the standard for comparing two objects is: compare() returns 0. It is no longer equal() --- > no more examples will be written here, which is similar to the comparison of common classes * */
5) , Map interface
① , notes
/* *5.Map interface *> map: double column data, storing data of key value pair *> HashMap: as the main implementation class of Map, thread is unsafe and efficient, and null key and value are stored *LinkedHashMap: ensure that when traversing map elements, you can implement traversal in the order you add them *> reason: Based on the original underlying structure of HashMap, a pair of pointers are added to point to the former and the latter elements. For frequent traversal operations, this kind of execution efficiency is higher than that of HashMap *Treemap: ensure to sort according to the added key value, and implement sorting traversal. At this time, consider the natural or customized sorting of key, and use red black tree at the bottom *> add key value to TreeMap, requiring that the key must be an object created by the same class *> because sorting by key: natural sorting, customized sorting * *> hashtable: as an old implementation class; thread safe and inefficient; cannot store null key and value *> properties: commonly used to process configuration files. Both key and value are of String type *> the bottom layer of HashMap *> JDK7: array + linked list *> jdk8: array + linked list + red black tree *> understanding of map structure *> key in map: unordered and non repeatable. Use Set to store all keys - > the class of key should override equals() and hashCode() (take HashMap as an example) *Value in > map: unordered, repeatable, use Collection to store all values -- > the class of value should override equals() *> a key value pair: key value constitutes an Entry object *> entry in map: unordered, non repeatable, use Set to store all entries *>Map bottom principle, later continued *> methods defined in map *Add, delete and modify: *Object put(Object key,Object value): add (or modify) the specified key value to the current map object *void putAll(Map m): store all key value pairs in m into the current map *Object remove(Object key): remove the key value pair of the specified key and return value *void clear(): clear all data in the current map *Operation of element query: *Object get(Object key): get the value corresponding to the specified key *boolean containsKey(Object key): whether to include the specified key *boolean containsValue(Object value): whether to include the specified value *int size(): returns the number of key value pairs in the map *boolean isEmpty(): judge whether the current map is empty *boolean equals(Object obj): judge whether the current map and parameter object obj are equal *How to operate the meta view: *Set keySet(): returns the set set composed of all keys *Collection values(): returns the collection set of all values *Set entrySet(): returns the set set composed of all key value pairs * *> summary: common methods: *Add: put(Object key,Object value) *Delete: remove(Object key) *Modify: put(Object key,Object value) *Query: get(Object key) *Length: size() *Traversal: keySet() / values() / entrySet() * * */
② , code
public class MapTest05 { @Test public void test1(){ Map map = new HashMap(); //add to map.put(null,123); } @Test public void test2(){ Map map = new HashMap(); map = new LinkedHashMap(); map.put(123,"AA"); map.put(345,"BB"); map.put(12,"CC"); //try System.out.println(map); } @Test public void test3(){ Map map = new HashMap(); //add to map.put("AA",123); map.put(45,123); map.put("BB",56); //modify map.put("AA",87); System.out.println(map); Map map1 = new HashMap(); map1.put("CC",123); map1.put("DD",123); map.putAll(map1); System.out.println(map); //remove(Object key) Object value = map.remove("CC"); System.out.println(value); System.out.println(map); //clear() map.clear();//Different from map = null operation System.out.println(map.size()); System.out.println(map); } @Test public void test4(){ Map map = new HashMap(); map.put("AA",123); map.put(45,123); map.put("BB",56); // Object get(Object key) System.out.println(map.get(45)); //containsKey(Object key) boolean isExist = map.containsKey("BB"); System.out.println(isExist); isExist = map.containsValue(123); System.out.println(isExist); map.clear(); System.out.println(map.isEmpty()); } @Test public void test5(){ Map map = new HashMap(); map.put("AA",123); map.put(45,1234); map.put("BB",56); //Traverse all key sets: keySet() Set set = map.keySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } System.out.println(); //Traverse all value sets: values() Collection values = map.values(); for(Object obj : values){ System.out.println(obj); } System.out.println(); //Traverse all key values //Mode 1: entrySet() Set entrySet = map.entrySet(); Iterator iterator1 = entrySet.iterator(); while (iterator1.hasNext()){ Object obj = iterator1.next(); //The elements in the entry set set are all entries Map.Entry entry = (Map.Entry) obj; System.out.println(entry.getKey() + "---->" + entry.getValue()); } System.out.println(); //Mode 2: Set keySet = map.keySet(); Iterator iterator2 = keySet.iterator(); while(iterator2.hasNext()){ Object key = iterator2.next(); Object value = map.get(key); System.out.println(key + "=====" + value); } } //Natural order @Test public void test6(){ TreeMap map = new TreeMap(new Comparator(){ @Override public int compare(Object o1, Object o2) { if(o1 instanceof User && o2 instanceof User){ User u1 = (User)o1; User u2 = (User)o2; return Integer.compare(u1.getAge(),u2.getAge()); } throw new RuntimeException("The type entered does not match!"); } }); User u1 = new User("Tom",23); User u2 = new User("Jerry",32); User u3 = new User("Jack",20); User u4 = new User("Rose",18); map.put(u1,98); map.put(u2,89); map.put(u3,76); map.put(u4,100); Set entrySet = map.entrySet(); Iterator iterator1 = entrySet.iterator(); while (iterator1.hasNext()){ Object obj = iterator1.next(); Map.Entry entry = (Map.Entry) obj; System.out.println(entry.getKey() + "---->" + entry.getValue()); } } //Custom sort @Test public void test7(){ TreeMap map = new TreeMap(); User u1 = new User("Tom",23); User u2 = new User("Jerry",32); User u3 = new User("Jack",20); User u4 = new User("Rose",18); map.put(u1,98); map.put(u2,89); map.put(u3,76); map.put(u4,100); Set entrySet = map.entrySet(); Iterator iterator1 = entrySet.iterator(); while (iterator1.hasNext()){ Object obj = iterator1.next(); Map.Entry entry = (Map.Entry) obj; System.out.println(entry.getKey() + "---->" + entry.getValue()); } } } class User implements Comparable{ private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { System.out.println("User equals()...."); if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (age != user.age) return false; return name != null ? name.equals(user.name) : user.name == null; } @Override public int hashCode() { //return name.hashCode() + age; int result = name != null ? name.hashCode() : 0; result = 31 * result + age; return result; } //Arrange by name and age public int compareTo(Object o) { if(o instanceof User){ User user = (User)o; //return -this.name.compareTo(user.name); int compare = -this.name.compareTo(user.name); if(compare != 0){ return compare; }else{ return Integer.compare(this.age,user.age); } }else{ throw new RuntimeException("Type of input does not match"); } } }
4. Traversal
1) , notes
/* *1. Traversal *> normal for loop *Iterator *for loop: foreach * * */
5. Collections
1) , notes
/* *1. Collection of tool class *> Collections: tool class for operation Collection and Map *> common methods *reverse(List): reverse the order of elements in the List *shuffle(List): random sorting of List collection elements *sort(List): sort the specified List collection elements in ascending order according to their natural order *sort(List, Comparator): sort the List collection elements according to the order generated by the specified Comparator *swap(List, int, int): exchange elements i and j in the specified list collection *Object max(Collection): returns the largest element in a given collection according to the natural order of the elements *Object max(Collection, Comparator): returns the largest element in a given collection according to the order specified by Comparator * Object min(Collection) * Object min(Collection,Comparator) *int frequency(Collection, Object): returns the number of occurrences of the specified element in the specified collection *void copy(List dest,List src): copy the contents of src to dest *Boolean replaceall (List, Object oldVal, Object newVal): replace all old values of List objects with new values * * */
② , code
public class CollectionsTest01 { @Test public void test2(){ List list = new ArrayList(); list.add(123); list.add(43); list.add(765); list.add(-97); list.add(0); //Exception reported: IndexOutOfBoundsException("Source does not fit in dest") //List dest = new ArrayList(); //Collections.copy(dest,list); //correct: List dest = Arrays.asList(new Object[list.size()]); System.out.println(dest.size());//list.size(); Collections.copy(dest,list); System.out.println(dest); //In the Collections class, multiple synchronizedXxx() methods are provided. This method can wrap the specified collection into a collection with thread synchronization, thus solving the thread safety problem when multiple threads access the collection concurrently //list1 returned is a thread safe List List list1 = Collections.synchronizedList(list); } @Test public void test1(){ List list = new ArrayList(); list.add(123); list.add(43); list.add(765); list.add(765); list.add(765); list.add(-97); list.add(0); System.out.println(list); //Collections.reverse(list); //Collections.shuffle(list); //Collections.sort(list); //Collections.swap(list,1,2); int frequency = Collections.frequency(list, 123); System.out.println(list); System.out.println(frequency); } }
6. Last
1) This chapter is almost finished. First, write down the underlying source code clearly, but it seems that there are too many. Later, write a chapter specifically
2) Thank you for your support. It's a long way to go