aggregate
Concept: when we need to save data, the types of data may be diverse, so there is a data structure. The implementation of the data structure in java is our collection
1. Multiple objects can be saved dynamically, which is convenient to use
2. Provide some convenient methods to add, delete and find
Collection API
Collection system overview: the Java collection framework is composed of some interfaces, abstract classes and concrete classes, all located in Java Util package
Collection interface
Some methods common to collections are defined in the Collection interface
These methods are summarized in code below
public static void main(String[] args) { Collection<String> c = new ArrayList<String>(); Collection<String> co = new ArrayList<String>(); c.add("asd");//Add a single element c.add("b"); c.add("c"); //c.clear();// Delete all System.out.println(c.remove("b"));//Delete the specified element, and the return value is boolean System.out.println(c.contains("a"));//Find the specified element, and the return value is of bolean type System.out.println(c.size());//length System.out.println(c.isEmpty());//Judge whether it is empty co.add("zxc"); co.add("c"); c.addAll(co);//Add all the elements in co to c System.out.println(c); //c.removeAll(co); //System.out.println(c);// Delete the specified collection, and delete the common elements when they are not included System.out.println(c.containsAll(co));//Finds the specified collection, and the return value is of bolean type }
List collection
1. The elements in the list interface are orderly (the addition order is consistent with the extraction order) and repeatable
2. Each element in the list interface has its corresponding sequential index
Some methods in the List interface:
public static void main(String[] args) { List list = new ArrayList(); list.add("a");//Add element list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("a"); list.add(0, "z");//Adds an element at the specified location System.out.println(list.get(2));//Gets the element at the specified location System.out.println(list.indexOf("a"));//Returns the first occurrence of the specified element in the collection System.out.println(list.lastIndexOf("a"));//Returns the last occurrence of the specified element in the collection list.set(0, "x");//Replace the element at the specified location System.out.println(list); list.remove(0);//Deletes the element at the specified location System.out.println(list); System.out.println(list.subList(0, 4));//Intercept the elements of the specified interval, close left and open right }
List has three traversal modes:
for loop:
public static void main(String[] args) { ArrayList arrayList = new ArrayList(); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("d"); arrayList.add("e"); arrayList.add("a"); arrayList.add("b"); for (int i = 0; i < arrayList.size(); i++) { System.out.println(arrayList.get(i)); } } }
Enhanced for:
public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList(); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("d"); arrayList.add("e"); arrayList.add("a"); arrayList.add("b"); for(String item : arrayList){ System.out.println(item); } }
Iterator iteration:
public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList(); arrayList.add("a"); arrayList.add("b"); arrayList.add("c"); arrayList.add("d"); arrayList.add("e"); arrayList.add("a"); arrayList.add("b"); System.out.println(arrayList); Iterator<String> iterator = arrayList.iterator(); while (iterator.hasNext()){ Object next = iterator.next(); System.out.println(next); } }
ArrayList implementation class
The underlying principle of arrayList is array. It is thread unsafe, but it is efficient
Capacity expansion mechanism: when creating an ArrayList object, if parameterless construction is used, when adding the first element, the capacity will be automatically expanded to 10. If it cannot be met, the capacity will be expanded by 1.5 times under the current capacity; If a certain capacity is given when using parameterless construction, the capacity will be expanded by 1.5 times based on the current capacity when the capacity cannot be met
LinkedList implementation class
The LinkedList bottom layer implements the characteristics of two-way linked list and double ended queue. Any element can be added, including null. The thread is unsafe and synchronization is not realized
Vector implementation class
The underlying layer of Vector is also an object array, which is thread synchronized, that is, thread safe, but the efficiency is not high, because it is synchronized. In the development process, when considering thread safety, consider using Vector
Capacity expansion mechanism: if it is a nonparametric structure, the default value is 10. When it is full, it will be expanded by twice the current capacity; If it is a parametric structure, specify the size and directly expand it by twice each time
Set interface
The elements stored in the Set cannot be repeated and contain at most one null
The elements in the Set are out of order, the order of fetching and adding are inconsistent, and there is no index
Some methods in the Set interface: since the Set interface inherits the Collection interface, the common methods are the same as those in the Collection interface
The traversal method of the Set interface is the same as that of the Collection interface. You can enhance the for iterator, but you can't get it by index
HashSet
HashSet implements the Set interface, which is actually a HashMap
null values can be stored, but there is only one element. The elements are out of order. The index is determined after hash
TreeSet
When a TreeSet object is created using a parameterless constructor, it is still unordered
When using its parameterized constructor (Comparator), you can specify the collation
public class TreeSetDemo { public static void main(String[] args) { TreeSet<Student> treeSet = new TreeSet(); treeSet.add(new Student("Xiao Ming", 12458)); treeSet.add(new Student("Xiao Hong", 12465)); treeSet.add(new Student("Xiaobai", 12452)); treeSet.add(new Student("Xiao Hei", 12450)); treeSet.add(new Student("Xiao Ming", 12451)); System.out.println(treeSet); } } class Student implements Comparable<Student>{ private String name; private int id; public Student(String name, int id) { this.name = name; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", id=" + id + '}'; } @Override public int compareTo(Student o) { //return this.name.compareTo(o.name); return this.id-o.id; } }
Map interface
The Map interface and the Collection interface exist side by side. If they are double columns, there is a pair of key value pairs (K-V)
The Key in the Map cannot be repeated, and the Value can be repeated The Key can be null, but there can only be one, and the Value can also be null, but there can be multiple
String is often used as the "Key" in Map
There is a one-way one-to-one relationship between Key and Value. The corresponding Value can be found through Key
Common methods:
public static void main(String[] args) { HashMap map = new HashMap(); map.put(10, "zz");//Add element map.put(15, "bb"); map.put(6, "kk"); map.put(23, "oo"); map.put(10, "zzzz"); System.out.println(map.isEmpty());//Judge whether it is empty System.out.println(map.remove(6));//Delete the specified key and return the corresponding value System.out.println(map.size());//Returns the number of key value pairs System.out.println(map.containsKey(15));//Finds whether the specified key exists System.out.println(map.containsValue("bb"));//Find the specified value System.out.println(map.get(23));//Gets the value corresponding to the specified key System.out.println(map.hashCode()); map.replace(23, "ttt");//Replace the value corresponding to the specified key System.out.println(map); }
HashMap, treemap and hashtable all implement the Map interface
HashMap | TreeMap | Hashtable | |
---|---|---|---|
null key | Can store one | No | |
sort | disorder | Implement Comparable interface | disorder |
Thread safety | unsafe | security |
The process of adding elements to ArrayList and its capacity expansion mechanism
ArrayList is an implementation class of the List interface. It is an array that grows dynamically according to requirements In Java, the standard length of an array is defined when it is created. Once it is given, it cannot be changed. Sometimes we need some dynamic arrays to store data. At this time, we can use ArrayList, but its thread is not safe. It stores data in the order of addition
The ArrayList is expanded by calling ensureCapacityInternal() when calling the add() method. By judging whether it is necessary to expand, the key method to call the expansion is the grow() method, and the space is expanded to 1.5 times of the original
We can see that it is actually by judging the size of the new array, and then copying the original array to the new array
Underlying implementation principle of HashMap
HashMap is stored in the form of an array with a default length of 16 and a linked list. Each array stores a linked list
When using the put method to add an element, the HashCoede method will be called first to judge its hash value, and then the remainder will be obtained through a specific operation to obtain the index in the array. If there is no element stored in the index position, it will be stored directly. If there is an element, it will be compared through the equals method. If the Key values are the same, the original value will be retained. If the Key values are different, the linked list will continue to be compared downward, Until the last element is also different, then insert this element
The capacity expansion mechanism of the array is doubled
When eight elements appear in one position, it will be considered that the Hash function is poorly designed, and the array length is greater than 64, it will be automatically converted to a red black tree to improve performance
Hashtable capacity expansion mechanism
The bottom layer has an array Hashtable$Entry [], with an initialization size of 11. When it reaches its critical value, that is, 11 * 0.75, it will be expanded according to 2 times + 1 of the current capacity
The difference between ArrayList and LinkedList
ArrayList | LinkedList | |
---|---|---|
storage | The bottom layer is implemented by array | Storage based on bidirectional linked list |
Occupied memory size | Large memory | Small memory |
Access efficiency | fast | slow |
Theoretically insert and delete on non primacy | slow | fast |
Generally speaking, if you want to query elements, you can use ArrayList. If you want to delete them, you can select LinkedList as soon as you insert them