1. Why use set
For example: storing data
Before, you can use arrays to store data. Arrays have great disadvantages. Once the length is determined, it cannot be modified. Therefore, if you delete or add elements, you need to move a lot of elements.
Array: only one data type can be put, either basic data type or reference data type
As described in the total row, you can use sets to solve this problem:
Advantages of set: high efficiency of deleting elements
Characteristics of a collection: a collection can have multiple data types (generally, generics are used, only one data type is stored), but it can only store reference data types
2. Structure of set
3. Application scenario of collection
When you need to integrate individuals of the same structure, consider using sets.
4.ArrayList
- Use of ArrayList
public class Test { public static void main(String[] args) { Collection collection=new ArrayList();//Interface new implementation class System.out.println("Is the collection empty:"+collection.isEmpty()); //(1) Add element collection.add("hello"); collection.add(new Date()); collection.add(123); collection.add("hello"); collection.add(new Person("lisli",29, Gender.male)); System.out.println("Set is empty:"+collection.isEmpty()); System.out.println("Number of elements in the collection:"+collection.size()); System.out.println(collection); System.out.println(collection.remove("hello")); //Delete the first hello //collection.clear(); System.out.println(collection); System.out.println(collection.contains(123)); Collection collection1=new ArrayList(); collection1.add("world1"); collection1.add("world2"); collection1.add("world3"); collection.addAll(collection1); System.out.println(collection); //Ergodic set System.out.println("---------------------------------------"); for(Object obj:collection){ System.out.println(obj);//Call toString() method by default } System.out.println("------------------Traverse elements by using iterators hasNext() ,next()---------------------------"); Iterator ite= collection.iterator(); while(ite.hasNext()){ //true means there is data in the collection. If it is false, it means there is no data in the collection. You can exit the cycle Object obj= ite.next(); System.out.println(obj); } } }
- The underlying structure of ArrayList
ArrayList: an encapsulation of an array of Object types
(1) When the parameterless construction method of ArrayList is called to create the ArrayList object
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //The initial length is 0, and there is space in the heap transient Object[] elementData; //Declare an array of Object type, no new Object public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; //Point to the array with length 0 }
(2) When the add() method is called for the first time to add elements, the initialization capacity of the array of Object type is 10
private int size; //The number of elements in the collection. The default value is 0 private static final int DEFAULT_CAPACITY = 10; public boolean add(E e) { ensureCapacityInternal(size + 1); //Call methods in this class elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) {//minCapacity has a value of 1 ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//Executed the first time the add method is called return Math.max(DEFAULT_CAPACITY, minCapacity); //return Math.max(10,1); } return minCapacity; } private void ensureExplicitCapacity(int minCapacity) { //The calculated minimum capacity is 10 modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) //10-0 > 0? True indicates that the array length is not enough grow(minCapacity); } private void grow(int minCapacity) { //10 // overflow-conscious code int oldCapacity = elementData.length; //oldCapacity= 0 int newCapacity = oldCapacity + (oldCapacity >> 1); //0 + 0 results in newCapacity=0 if (newCapacity - minCapacity < 0) //0-10<0 true newCapacity = minCapacity; //newCapacity=10; 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); //Array copy }
(3) When the add() method is called for the eleventh time, the array is expanded to 15
int newCapacity = oldCapacity + (oldCapacity >> 1);
To add, delete, and modify ArrayList is to add, delete, and modify array of Object type
Advantages of ArrayList: saving storage space and high efficiency of query by index
Disadvantages of ArrayList: it is inefficient to delete and add a large number of elements that need to be moved. It is inefficient to compare and judge them one by one according to the content search
- Use of LinkedList
public class Test2 { public static void main(String[] args) { Collection collection=new LinkedList();//Interface new implementation class System.out.println("Is the collection empty:"+collection.isEmpty()); //(1) Add element collection.add("hello"); collection.add(new Date()); collection.add(123); collection.add("hello"); collection.add(new Person("lisli",29, Gender.male)); System.out.println("Set is empty:"+collection.isEmpty()); System.out.println("Number of elements in the collection:"+collection.size()); System.out.println(collection); System.out.println(collection.remove("hello")); //Delete the first hello //collection.clear(); System.out.println(collection); System.out.println(collection.contains(123)); Collection collection1=new LinkedList(); collection1.add("world1"); collection1.add("world2"); collection1.add("world3"); collection.addAll(collection1); System.out.println(collection); //Ergodic set System.out.println("---------------------------------------"); for(Object obj:collection){ System.out.println(obj);//Call toString() method by default } System.out.println("------------------Traverse elements by using iterators hasNext() ,next()---------------------------"); Iterator ite= collection.iterator(); while(ite.hasNext()){ //true means there is data in the collection. If it is false, it means there is no data in the collection. You can exit the cycle Object obj= ite.next(); System.out.println(obj); } } }
- LinkedList
The underlying data structure of LinkedList is linked list, which uses two-way linked list
transient Node<E> first; //The default values are all null transient Node<E> last; public boolean add(E e) { linkLast(e); return true; } void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); //When the add method is called, the new Node creates the node object last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } //Private static inner class in LinkedList private static class Node<E> { E item; //Current elements to store Node<E> next; //Successor node Node<E> prev; //Precursor node Node(Node<E> prev, E element, Node<E> next) { //Create a node object this.item = element; this.next = next; this.prev = prev; } }
Advantages: deleting and adding need to move elements, high efficiency (but need to locate to elements first)
Disadvantages: in each element node, the space is specially increased to store the address of the next element, which takes up more space. The address of each node is discontinuous and irregular, resulting in low efficiency of query according to the index
- Use iterator object to traverse elements and add elements
public class Test2 { public static void main(String[] args) { List list=new ArrayList(); list.add("java"); list.add("hello"); list.add("world"); list.add("sql"); //Want to add elements when traversing a collection // Iterator ite= list.iterator(); ListIterator ite=list.listIterator(); while(ite.hasNext()){ Object obj=ite.next(); if(obj.equals("hello")){ ite.add("html"); } } System.out.println(list); } }
5. generic
Used to restrict the data types of elements stored in a collection when creating collection objects
Symbol used for generics < data type >
When generics work: before javac
public class Test { public static void main(String[] args) { //When creating a collection object, the data type of the elements stored in the collection can only be String List<String> list=new ArrayList<String>(); list.add("hello"); list.add("java"); list.add("world"); // list.add(123); } }
Classification of generics
(1) Generic interface
public interface Collection<E>{ //E represents a data type. When can I know this type } //When creating the implementation class object of the interface, you can know that in the following code, the data type represented by E is Integer Collection<Integer> coll=new ArrayList<Integer>();
(2) generic class
public class ArrayList<E>{ //When is the data type of E known? When is the ArrayList object created } ArrayList<String> al=new ArrayList<String>();
(3) Generic methods
public boolean add(E e) {} //E also represents a data type. The data type of E is exactly the same as that of ArrayList < E >. Therefore, the type of E is determined when the object of ArrayList is created
Generic methods for variable parameters:
(1) The variable parameter is JDK1.5
(2) Generics are also JDK 1.5
public class Test { public static void main(String[] args) { Client<String> client=new Client<String>();//The type of T is String client.show("hello"); //Generic method, the data type is clear when calling the method, which solves the problem of overloaded methods with the same number of parameters and different types in the same class client.fun("hello"); client.fun(123); client.fun(new Date()); //The generic method with variable parameters solves the problem of overloaded methods with different data types and numbers client.method("hello"); client.method("world1","world2","world3"); client.method(123); client.method(8.7,9.8,7.6,9.9); //Variable parameter is actually an array Client<Integer> client2=new Client<Integer>();//Integer when T is of type client2.show(123); } }