Overview of collections
Collection in Java refers to a series of interfaces and classes for storing data, which can solve complex data storage problems.
Guide: import java.util. *;
The simplified set frame diagram is as follows:
List. List
ArrayList
List is an interface:
public interface List<E> extends Collection<E>{...}
ArrayList is the most commonly used subclass of List (which implements other interfaces and inherits the parent class, of course).
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{...}
ArrayList is similar in use to arrays, and its capacity can be dynamically adjusted as needed, also known as dynamic arrays.
The biggest pain in arrays is fixed size (it can be changed, but it's troublesome)
The bottom of the Array List is implemented with arrays, so there are arrays in the name.
Example: Thai tour group
This example demonstrates the need to use generics in List s.
Settings: Thai tour group, agreed to accept only Girl, there is a Boy mixed in, compiled no problem, when receiving (output) according to Girl, will make mistakes.
import java.util.ArrayList; import java.util.List; public class TestArrayList { public static void main(String[] args) { // Opening a regiment List _Five-day Tour to Thailand = new ArrayList(); Girl _g1 = new Girl(); Girl _g2 = new Girl(); Girl _g3 = new Girl(); _Five-day Tour to Thailand.add(_g1); _Five-day Tour to Thailand.add(_g2); _Five-day Tour to Thailand.add(_g3); // Mix in Boy _b = new Boy(); _Five-day Tour to Thailand.add(_b); System.out.println("..."); // Pick someone up at the airport for (int i = 0; i < _Five-day Tour to Thailand.size(); i++) { Girl g = (Girl) _Five-day Tour to Thailand.get(i); } } } class Boy { } class Girl { }
The code is correct and the operation is wrong (the object is of Boy type, but it has to be converted to Girl type - type conversion exception)
Exception in thread "main"
java.lang.ClassCastException
ArrayList < E > uses generics
After JDK 1.5, generics were introduced to specify the types of elements in the list. Elements that do not conform to the type are not allowed to be added to the array, so that errors can be found in the compilation phase and the embarrassment of runtime errors can be avoided.
// Opening a regiment List<Girl> _Five-day Tour to Thailand = new ArrayList<Girl>(); ...... // Mix in Boy _b = new Boy(); //There is an error in the prompt code: Thai 5-day tour. add(_b);
ergodic
import java.util.*; public class ListTraversal { public static void main(String[] args) { m010Traversal(); m020 Thread Safe Edition(); } private static void m010Traversal() { System.out.println("=====ergodic"); List<String> lst = new ArrayList<String>(); lst.add("Monkey King"); lst.add("Zhu Bajie"); lst.add("Sha Wujing"); // (1) for (int i = 0; i < lst.size(); i++) { System.out.println("for Traversal sets:" + lst.get(i)); } // (2) for (String s : lst) { System.out.println("foreach Traversal sets:" + s); } // (3)Iterator, iterator. Elements used to traverse (iteratively access) collections Iterator<String> it = lst.iterator(); while (it.hasNext()) { System.out.println("Iterator Traverse:" + it.next()); } // (4)Java 8: Call the forEach() method to traverse the collection lst.forEach(s -> System.out.println("Lambda The expression traversal set:" + s)); } // The API document says that ArrayList is not synchronous, that is, it is insecure in a multithreaded environment. // Collections. synchronized List (...) turns it into a thread-safe list private static void m020 Thread Safe Edition() { System.out.println("=====Thread Safe Edition"); List<String> lst = new ArrayList<String>(); lst.add("Monkey King"); lst.add("Zhu Bajie"); lst.add("Sha Wujing"); // Solving Thread Safety Problem List<String> synList = Collections.synchronizedList(lst); for (String s : synList) { System.out.println("foreach Traversal sets:" + s); } } }
Iterator Principle gif: https://www.cnblogs.com/tigerlion/p/10706386.html
More ways
Collection correlation method
These methods belong to Collection class and can be inherited by subclasses. Therefore, they have strong generality. They can be used not only in List but also in Set.
Return type | Method name | describe |
---|---|---|
boolean | add(Object o) | Adding elements |
int | size() | Get the number of elements |
boolean | contains(Object o) | Determine whether a specified element exists |
boolean | remove(Object o) | Delete elements |
void | clear() | empty |
boolean | isEmpty() | Sentence blank |
Object[] | toArray() | Set Rotation Array |
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; public class TestCollection { public static void main(String[] args) { Collection<String> list = new ArrayList<>(); for (int i = 0; i < 100; i++) { list.add("s" + i); } System.out.println("size():" + list.size()); // lookup boolean contains = list.contains("s1"); System.out.println("contains(Object o):" + contains); boolean empty = list.isEmpty(); System.out.println("isEmpty():" + empty); // Set Rotation Array Object[] array = list.toArray(); System.out.println("toArray(): " + Arrays.toString(array)); // delete list.remove("s1"); System.out.println("remove(Object o):" + list); list.clear(); System.out.println("clear():" + list); } }
List correlation method
List's derived class object can be used, Set is not.
They are all index-related methods:
Return type | Method name | describe |
---|---|---|
void | add(int index, E element) | Adding elements at specified locations |
int | indexOf(Object o) | Gets the index of the specified element |
E | set(int index, E element) | Replace the element at the specified location and return the element before the update |
E | get(int index) | Gets the element of the specified index |
E | remove(int index) | Delete the element of the specified index |
import java.util.ArrayList; import java.util.List; public class TestList { public static void main(String[] args) { List<String> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add("s" + i); } list.add(3, "Sravasti"); int indexOf = list.indexOf("Sravasti"); System.out.println("List.indexOf(Object o):" + indexOf); String set = list.set(0, "Elder Zhao of the State of Shewei");// Returns the element before the update System.out.println("List.set(int index, E element):" + set); String get = list.get(0); System.out.println("List.get(int index):" + get); String remove = list.remove(3);// Returns deleted elements System.out.println("List.remove(int index):" + remove + list); } }
Source code analysis:
The bottom layer of ArrayList is implemented through arrays, which makes queries fast and add or delete slowly. The API document says that ArrayList is not synchronous, that is, it is not safe in a multithreaded environment, but efficient.
ArrayList expands to 1.5 times at a time.
private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; // > 1: Right Move 1 Bit = Divide by 2 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 = Arrays.copyOf(elementData, newCapacity); }
Vector
It's the same as Array List.
The element exceeds its initial size | Thread Safety | efficiency | |
---|---|---|---|
ArrayList | *150% | × | high |
Vector | *200% | √ | low |
Vector is an older class that has appeared in JDK 1.0 and is not recommended for use (Vector has appeared in the Blue Bridge Cup exercise, as long as you know its usage in that question is the same as Array List).
Although Vector is thread safe, it is not recommended for thread safety. The recommended scheme is as follows:
List<String> synList = Collections.synchronizedList(lst);
LinkedList
ArrayList is implemented by using arrays, which can query fast and add or delete slowly.
LinkedList is implemented by linked list, which is slow in query and fast in addition and deletion. It is suitable for occasions where large amounts of data are often inserted and deleted, and iterator Iterator traversal is suitable.
If you just insert data at the end of the list, LinkedList is less efficient than ArrayList, because LinkedList needs to create objects when it calls add, and ArrayList expands only when the capacity is insufficient.
LinkedList implements the List and Deque interfaces.
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
Characteristic methods (polymorphism cannot be used at this time):
Characteristic Method | explain |
---|---|
addFirst() | Header additions |
addLast() | Tail addition |
removeFirst() | Header deletion |
removeLast() | Tail deletion |
push() | Stacking, equivalent to addFirst() |
pop() | Out of the stack, equivalent to removeFirst() |
offer() | Entering the queue is equivalent to addLast() |
poll() | Out of the queue, equivalent to removeFirst() |
import java.util.LinkedList; public class TestLinkedList { public static void main(String[] args) { LinkedList<String> link = new LinkedList<String>(); // addFirst: Header Add Data link.addFirst("A"); link.addFirst("B"); link.addFirst("C"); link.removeFirst(); System.out.println(link); // addLast: Adding data at the end link.addLast("A"); link.addLast("B"); link.addLast("C"); link.removeLast(); System.out.println(link); link.clear();// empty // push: push elements into the stack, equivalent to addFirst() link.push("A"); link.push("B"); link.push("C"); // pop: Out of the stack, removeFirst() link.pop(); System.out.println("Stack" + link); link.clear();// empty // Adds the specified element to the end of the list (the last element). // offer: Queue entry: the add method is called, and add calls linkLast, just like addLast link.offer("A"); link.offer("B"); link.offer("C"); // poll: Out of the queue: removeFirst() is called link.poll(); System.out.println("queue" + link); } }
[B, A]
[B, A, A, B]
//Stack [B, A]
//Queue [B, C]
* Array Deque. Stack and Queue
- Stack: FIFO
- Queue: First in, first out
Deque (double-ended queue) is a sub-interface of Queue. Its implementation mechanism is similar to that of ArrayDeque and ArrayList. Object [] array is used to store collection elements, and when the capacity is insufficient, arrays can be reallocated.
Array Deque can be used as a stack and queue.
import java.util.*; public class TestArrayDeque { public static void main(String[] args) { m030 Stack(); m040 queue(); } static void m030 Stack() { System.out.println("=====Stack"); // push,pop(poll can also be) Deque<String> stack = new ArrayDeque<String>(); stack.push("A"); System.out.println(stack);// [A] stack.push("B"); System.out.println(stack);// [B, A] stack.push("C"); System.out.println(stack);// [C, B, A] System.out.println("peek()Accessing the first element:" + stack.peek());// C System.out.println("pop()Eject:" + stack.pop());// C System.out.println(stack);// [B, A] } static void m040 queue() { System.out.println("=====queue"); // offrt,poll(pop can also) Deque<String> queue = new ArrayDeque<String>(); queue.offer("A");// [A] System.out.println(queue); queue.offer("B");// [A, B] System.out.println(queue); queue.offer("C");// [A, B, C] System.out.println(queue); System.out.println("peek()Accessing the first element:" + queue.peek());// A System.out.println("poll()Eject:" + queue.poll());// A System.out.println(queue);// [B, C] } }
Operation results:
=====Stack [A] [B, A] [C, B, A] peek()Accessing the first element:C pop()Eject:C [B, A] =====queue [A] [A, B] [A, B, C] peek()Accessing the first element:A poll()Eject:A [B, C]