1, Assemble
1, Explain
Collection is a container provided by java, which can be used to store multiple reference type data. The basic type needs to be packaged into reference data type before it can be stored in the collection.
2, The difference between sets and numbers
- The length of the array is fixed. The length of the collection is variable.
- Collections store reference data types. If you want to store basic type data, you need to store the corresponding wrapper class type.
- Arrays can store
3, Single column set
A single column set is stored by a single element, which is equivalent to no key, corresponding to the value. A double column set has keys and values. A single column is where a single object is stored.
Collection: the root interface of a single column collection class, which is used to store a series of elements that conform to certain rules,
1, Collection collection
1, Explain
The collection set is the top-level parent interface of a single column set. The collection set has no index and cannot be traversed. However, sun company has an traverser that can traverse the data in it.
It has two important sub interfaces, namely
- java.util.List: List is characterized by ordered elements, repeatable elements and indexed elements;
- The main implementation classes of the List interface are Java util. ArrayList and Java util. LinkedList,
- ArrayList collection: implementation class, fast query, slow addition and deletion
- LinkedList set: implementation class, slow query, fast addition and deletion
- java.util.Set: Set is characterized by non repeatable elements and no index.
- The main implementation classes of the Set interface are Java util. HashSet and Java util. LinkedHashSet,java.util.TreeSet.
- LinkedHashSet set: implementation class, element access in order
- TreeSet collection: implementation class, which can sort the elements in the collection
2, Collection collection common methods
1. Add the given object to the current collection
//Public Boolean add (E): adds the given object to the current collection. // Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); col.add("Zhao Wei"); System.out.println("col aggregate:"+col);// col collection: [Fan Bingbing, Li Bingbing, Lin Xinru, Zhao Wei]
2. Empty all elements in the collection
//public void clear(): clear all elements in the collection // Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); col.add("Zhao Wei"); System.out.println("col aggregate:"+col);// col collection: [Fan Bingbing, Li Bingbing, Lin Xinru, Zhao Wei] // Empty all elements in the collection col.clear(); System.out.println("col aggregate:"+col);// col set: []
3. Delete the given object in the current collection
//Public Boolean remove (E): deletes the given object from the current collection. // Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); col.add("Zhao Wei"); // Delete the element Li Bingbing col.remove("Bing Bing Li"); System.out.println("col aggregate:"+col);// col collection: [Fan Bingbing, Lin Xinru, Zhao Wei]
4. Judge whether the current collection contains the given object
//public boolean contains(Object obj): judge whether the current collection contains the given object // Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); col.add("Zhao Wei"); boolean res1 = col.contains("I"); System.out.println("res1:"+res1);// false
5. Judge whether the current set is empty
//public boolean isEmpty(): judge whether the current collection is empty. // Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); col.add("Zhao Wei"); //Judge whether the current collection is empty. (judge whether there are elements in the set) boolean res3 = col.isEmpty(); System.out.println("res3:"+res3);// false
6. Return the number of elements in the collection
//public int size(): returns the number of elements in the collection. // Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); // Gets the number of elements in the collection System.out.println("Number of elements in the collection:"+col.size());// 3
7. Store the elements in the set into the array
//public Object[] toArray(): store the elements in the collection into an array // Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); // Store the elements in the collection into an array Object[] arr = col.toArray(); System.out.println(Arrays.toString(arr));// [Fan Bingbing, Li Bingbing, Lin Xinru]
3, Iterator
1, Explain
In program development, it is often necessary to traverse all elements in a single column set. To meet this requirement, JDK provides an interface java util. Iterator.
Iteration: that is, the general acquisition method of Collection elements. Before taking an element, first judge whether there is an element in the set. If so, take out this element and continue to judge. If there is any, take it out again. Always take out all the elements in the Collection. This extraction method is called iteration in technical terms.
2, Writing method
//The Collection collection provides a method to get iterators: //`public Iterator iterator(): get the iterator corresponding to the collection and use it to traverse the elements in the collection. // Common methods of Iterator interface //public E next(): returns the next element of the iteration. //public boolean hasNext(): returns true if there are elements that can be iterated. Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); col.add("Zhao Wei"); // Get iterator object Iterator<String> it = col.iterator(); // Loop to determine whether there are elements in the set that can be iterated while (it.hasNext()){ // Indicates that there are elements that can be iterated String e = it.next(); System.out.println(e); }
3, Considerations for iterators
- If there are no elements in the collection that can be iterated and the next method of the iterator continues to be used when obtaining the collection elements, a Java. Net will be thrown util. NoSuchElementException has no collection element exception. If you want to continue iterating over the collection, you need to retrieve an iterator
- During collection element iteration, if you add or remove elements in the collection, you will not be able to continue the iteration, and a concurrent modificationexception will be thrown. However, deletion can be solved. Instead of the deletion method of the collection, you can delete elements by using the deletion method of the iterator. Adding cannot be solved temporarily.
// Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); col.add("Zhao Wei"); // Gets the iterator object of the collection Iterator<String> it = col.iterator(); // Loop to determine whether there are elements in the set that can be iterated while (it.hasNext()) { // Get elements that can be iterated String e = it.next(); System.out.println(e); // Add element to collection //col.add("Gao Yuanyuan")// Report exception // Delete element //col.remove(e);// Report exception // If the iterated element is Li Bingbing, delete it if (e.equals("Bing Bing Li")){ it.remove(); } }
4, Iterator principle
When traversing the collection, first obtain the iterator object by calling the iterator() method of the t collection, and then use the hashNext() method to judge whether there is the next element in the collection. If so, call the next() method to take out the element. Otherwise, it indicates that the end of the collection has been reached, and stop traversing the element.
When Iterator iterator object traverses the collection, it internally uses pointer to track the elements in the collection. Before calling the next method of the Iterator, the Iterator's index is located before the first element and does not point to any element. After calling the next method of the Iterator for the first time, the Iterator's index will move back one bit, point to the first element and return the element. When calling the next method again, the Iterator's index will point to the second element and return the element, And so on, until the hasNext method returns false, indicating that the end of the collection is reached and the traversal of the element is terminated.
4, Enhanced for loop
1, Explain
The enhanced for loop (also known as the for each loop) is jdk1 5 later, a high-level for loop is specially used to traverse arrays and collections. Its internal principle is actually an Iterator iterator, so you can't add or delete elements in the collection during traversal.
2, Writing method
/*for(Data type of element (variable: Collection or array){ //Write operation code }*/ // Create a Collection object that restricts the type of elements in the Collection to String Collection<String> col = new ArrayList<>(); // Add an element to the col collection col.add("Fan Bingbing"); col.add("Bing Bing Li"); col.add("Lin Xinru"); col.add("Zhao Wei"); // Enhanced for loop traversal for (String e : col) { System.out.println(e); } String[] arr = {"Fan Bingbing","Bing Bing Li","Lin Xinru", "Zhao Wei"}; for (String e : arr){ System.out.println(e); } // Enhanced for loop shortcut: array name \ collection name for
3, Precautions for use
-
The enhanced for loop must have a traversed target, which can only be a Collection or an array;
-
The enhanced for (iterator) only appears as a traversal operation and cannot add or delete elements to the collection. Otherwise, a concurrent modificationexception will be thrown
5, Generics
1, Explain
Represents an unknown data type, and determines its specific data type when using it. The role of generics is to determine the specific type of an unknown type when creating an Object. When no generic type is specified, the default type is Object type.
When creating a collection, no data type is written in < > and everything can be saved, but conversion exceptions will occur when taking it out. If the type is specified, only one kind of data can be stored. This is where generics are needed. When defining, use generic types, and when using, determine their specific types.
2, Defining and using generic class notation
/*Modifier class class name < variables representing generics > {} Variables representing generics: can be any letter, for example: T,E class ArrayList<E>{ public boolean add(E e){ } public E get(int index){ } .... } When E is determined, the return value of the method and the type of the variable are determined. That is, E is String, and the return values and parameters of member variables and methods are String Equivalent to a template. */ public class MyArrayList<E> { //Define member variables E e; int age; String name; //When a member method is defined and the return type and parameter type are not known, the generic type is used as a placeholder. Confirm when using. public E method(E e){ return e; } } //Create a collection of String classes MyArrayList<String> list1 = new MyArrayList<>(); list.age = 10 list.name ="world" list1.e = "itheima"; String res1 = list1.method("itcast"); System.out.println("res1:"+res1);// itcast //Create a collection of Integer types MyArrayList<Integer> list2 = new MyArrayList<>(); list2.e = 100; Integer res2 = list2.method(10); System.out.println("res2:"+res2);// 10
3, Defining and using methods that contain generics
//Modifier < variable representing generics > return value type method name (parameter) {} // // Define methods with generics //If the class does not use generics, T cannot be written directly here, because it is not defined in a generic class public static <T> T method1(T t){ return t; } Integer i1 = method1(100);// The specific data type of the specified generic is Integer System.out.println(i1);// 100 String s = method1("itheima");// The specific data type of the specified generic is String System.out.println(s);// itheima
4, Defines and uses the writing of interfaces that contain generics
//Modifier interface interface name < variables representing generics > {} public interface IA<E> { public abstract void method1(E e); public default E method2(E e){ return e; } }
5, Implement the writing method containing generic interfaces
1. Determine the type of the generic when defining the implementation class
// The specific data types of interface generics are determined by implementing classes public class Imp1 implements IA<String> { @Override public void method1(String s) { } @Override public String method2(String s) { return null; } } // When creating an implementation class object, determine the specific data type of the interface generic Imp2<String> imp1 = new Imp2<>(); imp1.method1("itheima"); String s1 = imp1.method2("itcast"); System.out.println(s1);// itcast
2. The type of generic type is always uncertain until the object is created
// When implementing the interface, the class does not determine the specific data type of the interface generic, // Instead, the specific data type of the interface generic is determined when creating the implementation class object public class Imp2<E> implements IA<E> { @Override public void method1(E e) { System.out.println("Implementation class method1"); } @Override public E method2(E e) { return e; } } Imp2<Integer> imp2 = new Imp2<>(); imp2.method1(100); Integer i = imp2.method2(100); System.out.println(i);// 100
6, Summary
Generic type: it represents an unknown data type when defined, and its specific data type is determined when used.
Use a class with generics: when creating this class object, specify the specific data type of the generics
Use method with direction: when calling this method, determine the specific data type of the generic
Use interfaces with generics:
1. When creating an implementation class to implement an interface, specify the specific data type of the generic type
2. When creating an implementation class implementation interface, you do not know the specific data type of the generic type, but specify the specific data type of the generic type when creating an implementation class object
6, Generic wildcard
1, Explain
When you don't know what type of reception to use, you can use?,? Indicates an unknown wildcard. At this time, only data can be accepted, and data cannot be stored in the collection.
2, Writing method
public class Test { public static void main(String[] args) { // Relationship: String inherits Object,Integer inherits number, and number inherits Objec ArrayList<Object> list1 = new ArrayList<>(); ArrayList<String> list2 = new ArrayList<>(); ArrayList<Integer> list3 = new ArrayList<>(); ArrayList<Number> list4 = new ArrayList<>(); list2.add("itheima"); //method1(list1); method1(list2); //method1(list3); //method1(list4); //method2(list1); method2(list2); //method2(list3); //method2(list4); // Generics have no polymorphism //ArrayList<Object> list = new ArrayList<String>();// Compilation error } // Define a method that can receive the above four sets public static void method1(ArrayList list){ Object obj = list.get(0); list.add("jack"); System.out.println("obj:"+obj);// itheima System.out.println("list:"+list);// [itheima, jack] } public static void method2(ArrayList<?> list){ Object obj = list.get(0); //list.add("jack");// Compilation reports an error. Data cannot be stored, but data can be obtained System.out.println("obj:"+obj);// itheima System.out.println("list:"+list);// [itheima] } }
7, Restricted generics
1, Explain
When you set generics before, you can actually set them arbitrarily, as long as they are classes. However, the upper and lower limits of a generic can be specified in JAVA generics.
2, Writing method
public class Test { public static void main(String[] args) { /* Advanced use of wildcards -- restricted generics: Upper limit: <? Extensions class name > can only receive this class type or its subclass type Lower limit: <? Super class name > can only receive this class type or its parent class type */ // Relationship: String inherits Object,Integer inherits number, and number inherits Objec ArrayList<Object> list1 = new ArrayList<>(); ArrayList<String> list2 = new ArrayList<>(); ArrayList<Integer> list3 = new ArrayList<>(); ArrayList<Number> list4 = new ArrayList<>(); method1(list1); method1(list2); method1(list3); method1(list4); //method2(list1);// Compilation error //method2(list2);// Compilation error method2(list3); method2(list4); method3(list1); //method3(list2);// Compilation error method3(list3); method3(list4); } // Define a method that can only receive the above list3 and list4 sets public static void method2(ArrayList<? extends Number> list){ } // Define a method that can only receive the above list3, list4 and LIST1 sets public static void method3(ArrayList<? super Integer> list){ } // Define a method that can receive the above four sets public static void method1(ArrayList<?> list){ } // Define a method that can receive the above four sets public static void method(ArrayList list){ } }
8, Data structure
1, Explain
Data structure: in fact, it is the way to store and represent data. Common data structures: stack, queue, array, linked list and red black tree.
2, Stack structure
Stack, also known as stack, is a linear table with limited operation. Its limitation is that it is only allowed to insert and delete at one end of the table, and it is not allowed to add, find, delete and other operations at any other location.
characteristic:
- First in and then out (that is, the stored elements can only be taken out after the elements behind them are taken out in turn). For example, when the bullet is pressed into the cartridge clip, the first pressed bullet is below, and the second pressed bullet is above. When shooting, the bullet above can be ejected first, and then the bullet below can be ejected.
- The entrance and exit of the stack are at the top of the stack.
- Stack pressing: is to store elements. That is, the elements are stored at the top of the stack, and the existing elements in the stack move one position to the bottom of the stack in turn.
- Spring stack: that is, take elements. That is, take out the top position elements of the stack, and the existing elements in the stack move one position to the top of the stack in turn.
3, Queue structure
Queue, abbreviated as queue, is also a linear table with limited operation like stack. Its limitation is that it is only allowed to insert at one end of the table and take out and delete at the other end of the table.
characteristic:
- First in first out (that is, the elements stored in the front of the first one can be taken out only after the elements in front of it are taken out in turn). For example, when a small train passes through a cave, the front goes first and the rear goes in; the front comes out first and the rear comes out later.
- The entrance and exit of the queue occupy one side respectively
4, Array structure
Array is an ordered sequence of elements. Array opens up a continuous space in memory and stores elements in this space. Like a row of rental houses, there are 100 rooms, from 001 to 100, and each room has a fixed number. Through the number, you can quickly find the renter.
characteristic:
- Find elements: through the index, you can quickly access the elements at the specified location
- Adding and deleting elements is slow
- Add elements at the specified index position: you need to create a new array, store the specified new elements at the specified index position, and then copy the original array elements to the corresponding index position of the new array according to the index.
- Specify the index position to delete the element: you need to create a new array, copy the original array element to the corresponding index position of the new array according to the index, and the element with the specified index position in the original array will not be copied to the new array.
5, Linked list structure
linked list, By a series of nodes (each element in the linked list is called a node). Nodes can be generated dynamically at run time. Each node includes two parts: one is the data field for storing the data element, the other is the pointer field for storing the address of the next node, and the pointer field of the last node is null. We often say that the linked list structure has one-way linked list and two-way linked list. A single column has only the next A two-way linked list. A node has two pointers and a pointer field that stores the node addresses on both sides.
characteristic:
- Multiple nodes are connected by address. For example, many people hold hands. Each person uses his right hand to hold the next person's left hand, and so on, so that many people are connected together.
- Slow to find elements: to find an element, you need to find the specified elements backward through the connected nodes.
- Fast addition and deletion of elements: you only need to modify the address value of the next element linked
6, Tree structure
characteristic:
- Each node has zero or more child nodes
- A node without a parent node is called a root node, and a tree can have at most one root node.
- Each non root node has one and only one parent node
- There can be more than 2 child nodes.
noun | meaning |
---|---|
node | Refers to an element in the tree |
Degree of node | The number of subtrees owned by the node, and the degree of binary tree shall not be greater than 2 |
Leaf node | A node with a degree of 0 is also called a terminal node |
height | The height of the leaf node is 1, the height of the parent node of the leaf node is 2, and so on. The height of the root node is the highest |
layer | The root node is in the first layer, and so on |
Parent node | If a node has children, it is called parent of the its children |
Child node | The child node is the next level node of the parent node |
Sibling node | Nodes with common parent nodes are called siblings |
1. Binary tree
Explanation:
If the number of child nodes of each node in the tree does not exceed 2, the tree is a binary tree.
2. Binary lookup tree
characteristic:
- The value of all nodes on the left subtree is less than or equal to the value of its root node
- All node values on the right subtree are greater than or equal to the value of its root node
- Each child node can have at most two subtrees
- When traversing to obtain elements, you can traverse in the order of "left, middle and right"; The number to be taken out in this way is from small to large
- When obtaining elements, there are pre order: left and right, middle order: left, middle and right, and post order: left, middle and right. Different methods take elements in different order.
- Note: there is a problem with binary search tree: there will be "lame" phenomenon, which will affect the query efficiency
3. Balanced binary tree
1. Interpretation:
In order to avoid the phenomenon of "lame", reduce the height of the tree and improve our search efficiency, there is another tree structure: "balanced binary tree"
Rule: the absolute value of the height difference between the left and right subtrees is no more than 1, and both the left and right subtrees are a balanced binary tree.
2. Rotation
In the process of building a balanced binary tree, when there are new nodes to be inserted, check whether the balance of the tree is damaged due to the insertion. If so, rotate to change the structure of the tree. Rotation is done automatically.
3. Left hand rotation
Left rotation is to pull the right branch of the node to the left, turn the right child node into the parent node, and transfer the redundant left child node after promotion to the right child node of the degraded node
4. Right hand rotation
Pull the left branch of the node to the right, the left child node becomes the parent node, and transfer the redundant right child node after promotion to the left child node of the degraded node
5. Left left
Left left: you only need to do one right rotation to become a balanced binary tree.
6. Left and right
First do the left rotation of the branch and then the right rotation of the tree, so as to become a balanced binary tree.
7. Right
Right right: you only need to do left rotation once to become a balanced binary tree.
8. Right and left
First do the right rotation of the branch, and then do the left rotation again, so as to become a balanced binary tree.
4. Red black tree
Red black tree is a self balanced binary search tree and a data structure used in computer science. It was invented by Rudolf Bayer in 1972. At that time, it was called balanced binary B tree. Later, it was introduced by leoj in 1978 Guibas and Robert Sedgewick changed to today's "red black tree". It is a special binary search tree. Each node of the red black tree has a storage bit to represent the color of the node, which can be red or black; The red black tree is not highly balanced, and its balance is realized through "the characteristics of red black tree";
Characteristics of red black tree:
- Each node is either red or black.
- The root node must be black
- Each leaf node (Nil) is black; (if a node has no child node or parent node, the corresponding pointer attribute value of the node is Nil, and these Nils are regarded as leaf nodes)
- If a node is red, its child nodes must be black (two red nodes cannot be connected)
- For each node, the simple path from the node to all its descendant leaf nodes contains the same number of black nodes;
When inserting elements, it is the same as before; After each insertion, the black rules are used for verification. If the red and black rules are not met, the tree needs to be adjusted by color change, left rotation and right rotation to meet the red and black rules;
- The role of red black tree: improving search efficiency
- There are many classes representing collections, but each collection stores data in different data structures, so each collection has its own characteristics,
- ArrayList set: fast query, slow addition and deletion - > the data structure for storing data is array
- LinkedList set: slow query, fast addition and deletion - > the data structure for storing data is linked list
9, list interface
1, Explain
java. util. The List interface inherits from the Collection interface and is an important branch of a single column Collection. It is customary to call the objects that implement the List interface a List Collection.
2, Characteristics
- It is an ordered collection of elements. For example, the order of storing elements is 11, 22, 33. Then, the storage of elements in the set is completed in the order of 11, 22 and 33).
- It is a collection with an index. Through the index, you can accurately operate the elements in the collection (the same reason as the index of an array).
- There can be duplicate elements in the collection.
- . ArrayList class. All the methods in this class are defined from the list. Is a subclass of the list interface.
3, list interface common methods
As a sub interface of the Collection, list not only inherits all the methods in the Collection interface, but also adds some unique methods to operate the Collection according to the element index. How to see whether it is a new method depends on whether the method needs to be indexed. The method that needs to be indexed is added to the list. The Collection cannot have an index because it needs to provide methods to the list and set, and the set interface has no index.
1. Add the specified element to the specified position in the collection.
//public void add(int index, E element): adds the specified element to the specified position in the collection. // Create a list collection and restrict the type of elements in the collection to String type List<String> list = new ArrayList<>(); // Add some elements to the collection list.add("Miss Wang"); list.add("Miss Li"); System.out.println(list);// [Miss Wang, Miss Li] // Add Mr. Zhang at the position with index 1 list.add(1, "Miss Zhang"); System.out.println(list);// [Mr. Wang, Mr. Zhang, Mr. Li] //Two add are different methods
2. Return the element at the specified position in the collection.
//public E get(int index): returns the element at the specified position in the collection. List<String> list = new ArrayList<>(); // Add some elements to the collection list.add("Miss Wang"); list.add("Miss Li"); System.out.println(list);// [Miss Wang, Miss Li] // Add Mr. Zhang at the position with index 1 list.add(1, "Miss Zhang");// [Mr. Wang, Mr. Zhang, Mr. Li] // Gets the element with index 1 System.out.println("Element with index 1:"+list.get(1));// Miss Zhang
3. Remove the element at the specified position in the list and return the removed element.
List<String> list = new ArrayList<>(); // Add some elements to the collection list.add("Miss Wang"); list.add("Miss Li"); System.out.println(list);// [Miss Wang, Miss Li] // Add Mr. Zhang at the position with index 1 list.add(1, "Miss Zhang");// [Mr. Wang, Mr. Zhang, Mr. Li] // Delete teacher with index 1 String removeE = list.remove(1); System.out.println("Deleted element:"+removeE);// Miss Zhang
4. Replace the element at the specified position in the collection with the specified element, and return the element before the update of the value
//public E set(int index, E element): replaces the element at the specified position in the set with the specified element, and returns the element before the update of the value // Create a list collection and restrict the type of elements in the collection to String type List<String> list = new ArrayList<>(); // Add some elements to the collection list.add("Miss Wang"); list.add("Miss Li"); System.out.println(list);// [Miss Wang, Miss Li] // Add Mr. Zhang at the position with index 1 list.add(1, "Miss Zhang");// [Mr. Wang, Mr. Zhang, Mr. Li] // Replace the element with index 0 with Miss Zhao String setE = list.set(0, "Miss Zhao"); System.out.println("Replaced element:"+setE);// Miss Zhang
11, Implementation class of list interface
1, ArrayList collection
java. util. The structure of the ArrayList collection data store is an array structure. The addition and deletion of elements are slow and the search is fast. Because the functions most used in daily development are querying data and traversing data, ArrayList is the most commonly used collection.
2, LinkedList collection
java. util. The structure of LinkedList set data storage is linked list structure. A collection that facilitates the addition and deletion of elements. LinkedList is a two-way linked list. LinkedList provides a large number of methods for head and tail operations.
public class Test { public static void main(String[] args) { /* LinkedList Collection specific methods: - public void addFirst(E e):Inserts the specified element at the beginning of this list. - public void addLast(E e):Adds the specified element to the end of this list. - public E getFirst():Returns the first element of this list. - public E getLast():Returns the last element of this list. - public E removeFirst():Removes and returns the first element of this list. - public E removeLast():Removes and returns the last element of this list. - public E pop():Pop an element from the stack represented by this list. removeFirst() - public void push(E e):Pushes an element onto the stack represented by this list. addFirst() */ // Create a LinkedList collection and restrict the type of collection elements to String type LinkedList<String> list = new LinkedList<>(); // Add elements to the collection list.add("Cai Xukun"); list.add("Lu Han"); list.add("Kris"); System.out.println(list);// [Cai Xukun, Lu Han, Wu Yifan] // Add an element at the beginning and end of the collection list.addFirst("Luo Zhixiang"); list.addLast("Edison Chan"); System.out.println(list);// [Luo Zhixiang, Cai Xukun, Lu Han, Wu Yifan, Chen Guanxi] // Gets the beginning and end elements of the collection String firstE = list.getFirst(); String lastE = list.getLast(); System.out.println("The first element is:"+firstE);// Luo Zhixiang System.out.println("The last element is:"+lastE);// Edison Chan // Delete first and last elements String removeFirst = list.removeFirst(); String removeLast = list.removeLast(); System.out.println("The first element to be deleted is:"+removeFirst);// Luo Zhixiang System.out.println("The last element deleted is:"+removeLast);// Edison Chan System.out.println(list);// [Cai Xukun, Lu Han, Wu Yifan] // Pop -- > delete the first element String popE = list.pop(); System.out.println("The first element to be deleted is:"+popE);// Cai Xukun System.out.println(list);// [Lu Han, Wu Yifan] // Push -- > add an element at the beginning list.push("Cai Xukun"); System.out.println(list); // [Cai Xukun, Lu Han, Wu Yifan] } }