Relationships and usage of Collection,List,Set
1. Overview and use of Collection collections
Summary:
- Is the top-level interface to a single-column Collection that represents a set of objects, also known as elements of a Collection
- JDK does not support any direct implementation of this interface; it provides more specific subinterface (List and Set) implementations
Objects that create Collection collections:
-
polymorphic Ways
-
Specific implementation class ArrayList,LinkedList
2. Java Collection Architecture
3. Collection
- Collection collection common methods
[External chain picture transfer failed, source may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-HcyUTCQx-163167820) (C:\UsersZ09J1672AppDataRoamingTyporatypora-user-imagesimage-queue.png)]
- Store and traverse Mentor objects
public static void CollectionMentor(){ Collection<Mentor> c = new ArrayList<>(); Mentor m1 = new Mentor("Iwakawa Riyu" , 18); Mentor m2 = new Mentor("M Brother" , 22); Mentor m3 = new Mentor("Lavender Egg Rabbit" , 20); c.add(m1); c.add(m2); c.add(m3); Iterator<Mentor> it = c.iterator(); while (it.hasNext()){ Mentor m = it.next(); System.out.println(m); System.out.println(m.getName()+","+m.getAge()); } }
3.1 List Collection
List Collection Overview and Features
Summary:
- An ordered collection, also known as a sequence, in which the user can precisely control the insertion order of each element in the list, access elements through an integer index, and search for elements in the list
- Unlike Set collections, lists allow duplicate elements
Characteristic:
- Ordered: elements stored and removed in the same order
- Repeatable: Stored elements can be repeated
List Collection Specific Methods
Note: E stands for element
In addition to iterator traversal, lists can also be traversed with a for loop + get(int index)
//Traverse List Collection for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); }
Concurrent Modification Exception
CocurrentModificationException: When such modifications are not allowed, this exception can be thrown by detecting concurrent modifications to the object.
public static void ListMentor(){ List<Mentor> c = new ArrayList<>(); Mentor m1 = new Mentor("Iwakawa Riyu" , 18); Mentor m2 = new Mentor("M Brother" , 22); Mentor m3 = new Mentor("Lavender Egg Rabbit" , 20); c.add(m1); c.add(m2); c.add(m3); Iterator<Mentor> it = c.iterator(); while (it.hasNext()){ Mentor m = it.next(); if(m.getName().equals("Iwakawa Riyu")){ c.add(new Mentor("Marry me",21)); } System.out.println(m); System.out.println(m.getName()+","+m.getAge()); } }
Run Results
Causes
- During iterator traversal, the length of elements in a collection is modified through a collection object, resulting in inconsistencies in the iterator's acquisition of elements between the expected and actual modified values (detailed principles allow you to see the ArrayList source code)
Source Code Analysis (only extract relevant code)
List-> AbstractList-> ArrayList-> iterator()-> new Iter()-> next()-> checkForComodification()
public interface List<E> extends Collection<E> { void add(int index, E element); Iterator<E> iterator(); } public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { protected transient int modCount = 0; } //modCount: Number of times the collection was actually modified //expectedModCount: Number of times the collection is expected to be modified public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { public Iterator<E> iterator() { return new Itr(); } public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } private void ensureExplicitCapacity(int minCapacity) { modCount++;//modCount here+1 } private class Itr implements Iterator<E> { int cursor; int lastRet = -1; int expectedModCount = modCount;//Since the AbstractList class is inherited, modCount is accessible Itr() {} public boolean hasNext() { return cursor != size; } public E next() { checkForComodification(); } //In the example, after calling the next method, the add() method, modCount+1 in the add() method, is called again, so after the next call to the checkForComodification() method in the next() method, because modCount!=ExpectedModCount, so report and modify exceptions final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } }
Solution One
- Traverse with a for loop and do the corresponding operation with the collection object
for(int i = 0;i<c.size();i++){ Mentor m = c.get(i); if(m.getName().equals("Iwakawa Riyu")){ c.add(new Mentor("Marry me",21)); } System.out.println(m.getName()+","+m.getAge()); }
Solution 2
- Using ListIterator:List Iterator
- Obtained by the listIterator() method of the List collection, so it is a unique iterator of the List collection
ListIterator<Mentor> lit = c.listIterator(); while (lit.hasNext()){ Mentor m = lit.next(); if(m.getName().equals("Iwakawa Riyu")){ lit.add(new Mentor("Marry me",21)); } System.out.println(m.getName()+","+m.getAge()); }
LinkedList-specific methods
3.2 Set Collection
Set Collection Overview and Features
Summary:
- A collection that does not contain duplicate elements and has at most one empty element
Characteristic:
- Does not contain duplicate elements
- There is no indexed method, so normal for loop traversal cannot be used
public static void setMethod(){ Set<String> set = new HashSet<>(); //HashSet: The underlying data structure is a hash table with no guarantee of the iteration order of the set set.add("hello"); set.add("world"); set.add("java"); set.add("world"); for(String s : set){ System.out.println(s); } }
Run Results