catalogue
1. Differences between sets and arrays:
2. Features of the collection:
1. Various functions in Collection:
1. Use the acquisition function to realize traversal:
3, List interface (inherited from Collection interface)
1. Features of List interface:
2. List related sets have the following functions:
1, Overview of collections:
Example: use the array to store three student information, and traverse the array to obtain each student information.
The implementation of this example is relatively simple, but when the information of a new student suddenly needs to be added to the array, you need to re create an array with a length of four for re implementation. If there is too much data, you need to constantly create a new array to store. Such an operation is very cumbersome, so Java can according to different elements, Elements have different characteristics and storage methods, and a collection inheritance mechanism is provided for use.
1. Differences between sets and arrays:
1. The length of the array is immutable, and the length of the set is variable
2. Arrays can store elements of the same basic data type or reference data type, while collections can only store elements of reference data types, but collections can store elements of different reference data types. (in actual development, only one reference data type element is stored in a collection)
2. Features of the collection:
Collection is only used to store objects; A variable length set; Collections can hold different types of objects.
Collections are not single. Different collections provided by Java are used for different needs. These different sets should have some commonness. According to the commonness between them, they should be extracted upward, and finally form an inheritance mechanism.
Inheritance system (mechanism) of collection
Sketch:
2, Collection interface:
Is the top-level interface of a collection, and it has an inheritance system developed by it
Because Collection is an interface, it cannot be instantiated. We need to find a subclass to instantiate the interface in a polymorphic way. For the time being, use ArrayList as an example
1. Various functions in Collection:
1. Add features:
boolean add(Object e) ensures that this collection contains the specified element (optional operation)
boolean addAll (Collection c) adds all elements of the specified collection to this collection (optional)
2. Delete function:
boolean remove (Object o) removes a single instance (if any) of the specified element from the collection
boolean removeAll (Collection c) deletes all elements of this collection contained in the specified collection
void clear() removes all elements from this collection
3. Get function:
Iterator iterator() returns the iterator of the elements in this collection
4. Judgment function:
boolean contains (Object o) returns true if the collection contains the specified element
boolean containsAll (Collection c) returns true if the collection contains all elements in the specified collection
boolean isEmpty() returns true if the collection does not contain elements
5. Get length method:
int size() returns the number of elements in this collection
6. Intersection function:
Boolean retain all (Collection c) retains only the elements contained in the specified collection in this collection
7. Convert collection to array:
Object[] toArray() returns an array containing all the elements in this collection
Specific part realization:
import java.util.ArrayList; import java.util.Collection; public class Test1 { public static void main(String[] args) { Collection c=new ArrayList(); // Add function of Collection: c.add("hello"); c.add("world"); c.add("java"); c.add("bigdata"); System.out.println("Added collection:"+c); // Delete function of Collection remove: c.remove("world"); System.out.println("Deleted collection:"+c); // Judgment function of Collection: System.out.println("Determine whether it contains world: "+c.contains("world")); // Judge whether it is empty: System.out.println("Judge whether it is empty:"+c.isEmpty()); // Get length: System.out.println("The length of the collection is"+c.size()); // Delete function of Collection clear: c.clear(); System.out.println("Cleared collection:"+c); } }
Output result:
For functions used between two sets, the implementation is as follows:
import java.util.ArrayList; import java.util.Collection; /* boolean addAll(Collection c) Optionally, add all elements in the specified collection to this collection boolean removeAll(Collection c) Delete all elements in this collection (optional). boolean containsAll(Collection c) Returns true if the collection contains all the elements in the specified collection. boolean retainAll(Collection c) Keep only the elements in this collection that are included in the specified collection (optional operation). */ public class Test2 { public static void main(String[] args) { Collection c1 = new ArrayList(); c1.add("hello"); c1.add("world"); c1.add("java"); c1.add("bigdata"); System.out.println(c1); Collection c2=new ArrayList(); c2.add("hello"); c2.add("world"); c2.add("superman"); System.out.println(c2); System.out.println("=============================================="); System.out.println("take c2 Add to c1: " ); c1.addAll(c2); System.out.println(c1); System.out.println(c2); System.out.println("=============================================="); System.out.println("judge c1 Include c2: "); boolean b = c1.containsAll(c2); System.out.println(b); System.out.println("=============================================="); System.out.println("c1 Keep only c2 Elements in(intersect ): "); // Take intersection function c1.retainAll(c2); System.out.println(c1); System.out.println(c2); // When c1 intersects with c2, the result is saved in c1, c2 remains unchanged, and c1 deletes elements that are not common with c2 System.out.println("=============================================="); System.out.println("take c1 Delete include from c2 Elements in:"); c1.removeAll(c2); System.out.println(c1); System.out.println(c2); } }
Output result:
2, Traversal of collection:
The purpose is to extract the elements in the set in turn
Use function 7: convert a collection into an array: toArray() method
The specific implementation is to convert the set into an array, and then traverse the array:
import java.util.ArrayList; import java.util.Collection; public class Test3 { public static void main(String[] args) { Collection c=new ArrayList(); c.add("hello"); c.add("world"); c.add("java"); c.add("bigdata"); // Use toArray() to convert a collection to an array Object[] objects = c.toArray(); // Traverse the array for(int i=0;i< objects.length;i++){ System.out.println(objects[i]);//Object o = objects[i](String type) /* The Object type is used here, but it is actually a String type This forms a polymorphism */ } } }
Output result:
If you want to get the length of each string element, directly add a line of statement:
System.out.println(objects[i].length());
An error will be reported: because polymorphism is used here, the compiler will look at the left and the operation will look at the right. There is no length() method in the Object class.
Therefore, it needs to be transformed downward. The specific code is as follows:
import java.util.ArrayList; import java.util.Collection; public class Test3 { public static void main(String[] args) { Collection c=new ArrayList(); c.add("hello"); c.add("world"); c.add("java"); c.add("bigdata"); // Use toArray() to convert a collection to an array Object[] objects = c.toArray(); // Since it is not clear what data type the collection will be after it is converted into an array, the Object [] type is used to receive // Traverse the array for(int i=0;i< objects.length;i++){ // System.out.println(objects[i]); // Get the length of each string element: // Downward Transformation: String s=(String)objects[i]; System.out.println(s+"---"+s.length()); } } }
Output result:
Student examples:
import java.util.ArrayList; import java.util.Collection; /* Requirements: add 3 student objects to the collection and traverse student information */ public class Test3a { public static void main(String[] args) { // Create collection object Collection c=new ArrayList(); // Create student object Student s1=new Student("ma chao",18); Student s2=new Student("Guan Yu",17); Student s3=new Student("Fei Zhang",16); // Add student object to collection c.add(s1); c.add(s2); c.add(s3); // Convert a collection to an array Object[] objects = c.toArray(); // Traversal array for (int i=0;i<objects.length;i++){ // Downward transformation Student s=(Student)objects[i]; System.out.println(s.getName()+"---"+s.getAge()); } } }
Output result:
1. Use the acquisition function to realize traversal:
Iterator iterator() returns the iterator of the elements in this Collection. It is a proprietary way of traversing collections
An iterator is an interface
Two main methods:
boolean hasNext() determines whether there are elements in the iterator
Object next() returns the elements in the iterator
Traversal using iterators:
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Test4 { public static void main(String[] args) { Collection c=new ArrayList(); c.add("hello"); c.add("world"); c.add("java"); c.add("bigdata"); // Get iterator object Iterator iterator = c.iterator();//Iterator iterator = new Itr(); // The concrete implementation of this interface is the class Itr() // System.out.println(iterator);//java.util.ArrayList$Itr@4554617c // Use next() to get the next element Object next = iterator.next(); System.out.println(next);//Get hello System.out.println(iterator.next());//Get world System.out.println(iterator.next());//Get java System.out.println(iterator.next());//Get bigdata // System.out.println(iterator.next());//NoSuchElementException /* When the next method is inadvertently used more than once, an error is reported The reason is that the traversal has been executed to the last element and should not point to the next element. It is redundant */ } }
Output result:
Solution to the problems in the above code: add judgment: hasnext() before executing the next method
The following is the improvement Code:
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Test4 { public static void main(String[] args) { Collection c=new ArrayList(); c.add("hello"); c.add("world"); c.add("java"); c.add("bigdata"); // Get iterator object Iterator iterator = c.iterator();//Iterator iterator = new Itr(); // The concrete implementation of this interface is the class Itr() // System.out.println(iterator);//java.util.ArrayList$Itr@4554617c // Solution: add judgment: hasnext() before executing the next method if(iterator.hasNext()){ System.out.println(iterator.next()); } if(iterator.hasNext()){ System.out.println(iterator.next()); } if(iterator.hasNext()){ System.out.println(iterator.next()); } if(iterator.hasNext()){ System.out.println(iterator.next()); } if(iterator.hasNext()){ System.out.println(iterator.next()); } } }
The output result is the same as above, but after adding judgment here, if judgment and next method are used five times, but the final result is not affected. If the amount of data added to the collection is too large, the number of if statements is not clear. Here, use the while loop to further improve.
The final improvement code is:
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class Test4 { public static void main(String[] args) { Collection c=new ArrayList(); c.add("hello"); c.add("world"); c.add("java"); c.add("bigdata"); // Get iterator object Iterator iterator = c.iterator();//Iterator iterator = new Itr(); // The concrete implementation of this interface is the class Itr() // System.out.println(iterator);//java.util.ArrayList$Itr@4554617c // Use the while loop to improve: while(iterator.hasNext()){ Object next = iterator.next(); String s=(String)next; System.out.println(s+"---"+s.length()); } } }
Final output:
1. Can I change the while loop to a for loop?
Yes, but it is generally not recommended to use ordinary for loop traversal
2. Why does java define iterator as an interface rather than a class?
The method of traversing a collection is different from that of directly storing the data in the future. Therefore, it is very possible to use the iterator in different ways in the future, Instead, it provides a unique collection class of the interface in the future to implement the value taking method in the interface to realize its own value taking characteristics.
Relevant cases:
Store custom objects and traverse:
First define a Student class:
public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Secondly, the relevant codes are as follows:
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /* Store custom objects and traverse */ public class CollectionTest2 { public static void main(String[] args) { //1. Create collection object Collection c = new ArrayList(); //2. Create student object Student s1 = new Student("Fei Zhang", 17); Student s2 = new Student("Guan Yu", 18); Student s3 = new Student("Zhao Yun", 19); Student s4 = new Student("Huang Zhong", 20); Student s5 = new Student("ma chao", 21); //3. Add student object to collection c.add(s1); c.add(s2); c.add(s3); c.add(s4); c.add(s5); //4. Traversal set //Get iterator object Iterator iterator = c.iterator(); //Traversing iterators to get elements while (iterator.hasNext()) { Student s = (Student) iterator.next(); System.out.println(s.getName() + "---" + s.getAge()); } } }
Output result:
3, List interface (inherited from Collection interface)
1. Features of List interface:
1. The elements in the List set are ordered (in the same order of storage and retrieval). They store 1,2,3,4,5 and output 1,2,3,4,5
2. The List collection contains the concept of index
3. The elements in the List collection can be repeated
Relevant cases:
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListTest1 { public static void main(String[] args) { // Create a List collection object List list=new ArrayList(); // Add element list.add("hello"); list.add("world"); list.add("java"); list.add("bigdata"); // ergodic Iterator iterator=list.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } }
Output result:
2. List related sets have the following functions:
Because the List set has the concept of subscript index, a unique method is derived from this concept:
1. Add features:
void add(int index, Object element)
Optionally, inserts the specified element into the specified location in this list.
2. Delete function:
Object remove(int index) deletes the element at the specified position in the list (optional operation).
3. Get function:
Object get(int index) returns the element at the specified position in this list.
4. Modification function:
Object set(int index, Object element) replaces the element at the specified position in this list with the specified element (optional operation).
5. List collection specific iterators
ListIterator listIterator() returns the list iterators in the list (in the appropriate order).
Implementation of functions 1 to 4:
import java.util.ArrayList; import java.util.List; public class ListTest2 { public static void main(String[] args) { List list=new ArrayList(); list.add("hello"); list.add("world"); list.add("java"); list.add("bigdata"); System.out.println(list); // Add features: list.add(0,"hadoop"); System.out.println(list); list.add(2,"hive"); System.out.println(list); list.add(6,"spark"); System.out.println(list); // list.add(10,"flink"); // System.out.println(list);//IndexOutOfBoundsException // There will be an index out of bounds exception, so the range of added indexes is: // 0 < = index < = size(), if it exceeds the range, it will be abnormal System.out.println("============================================"); System.out.println("Before deletion:\r\n"+list); // Delete function: System.out.println(list.remove(3)); System.out.println("After deletion:\r\n"+list); System.out.println("============================================"); // Get function: System.out.println("Get element:"+list.get(4)); System.out.println(list); System.out.println("============================================"); // Modification function: Object o = list.set(4, "Superman"); System.out.println("Modified element:"+o); System.out.println(list); } }
Output result:
List specific iterators:
ListIterator listIterator() returns the list iterators in the list (in the appropriate order).
public interface ListIterator extends Iterator
Because it inherits from the Iterator interface, there must be hasNext() and next() methods inside
It also contains the following methods:
Object previous() returns the previous element of the list and moves the cursor position backward
This method can be called repeatedly to traverse the list backward, or mixed back and forth with the call to next().
1. This method is to get the previous element in the collection
2. The pointer of the element obtained by this method is the same as that obtained by next()
Note: if you want to traverse backwards, you must traverse positively and move the pointer to the end first. Not commonly used in development, but may be asked in an interview.
boolean hasPrevious() returns true. If the reverse list is traversed, the list iterator has multiple elements. Judge whether there is an element in the previous position. If there is an element, return true. If there is no element, return false.
Code example:
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class ListDemo3 { public static void main(String[] args) { //1. Create a List collection object List list = new ArrayList(); //2. Add element to collection list.add("hello"); list.add("world"); list.add("java"); list.add("bigdata"); //3. Traversal // Object previous = listIterator.previous(); // System.out.println(previous); //NoSuchElementException // If you directly use previous, an error will be reported because the cursor is in the first position and there is no previous element ListIterator listIterator = list.listIterator(); while (listIterator.hasNext()) { String s = (String) listIterator.next(); System.out.println(s + ",The length of the string is:" + s.length()); } System.out.println("==============use previous================"); while (listIterator.hasPrevious()){ Object previous = listIterator.previous(); System.out.println(previous); } } }
Output result:
The unique traversal method of List collection: the combination of size() and get() methods:
Specific implementation: the three methods are implemented together:
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListTest3 { public static void main(String[] args) { List list=new ArrayList(); Student s1=new Student("Liu Bei",51); Student s2=new Student("Cao Cao",45); Student s3=new Student("Sun Quan",40); list.add(s1); list.add(s2); list.add(s3); // ergodic // a: Convert to array traversal Object[] obj = list.toArray(); for(int i=0;i< obj.length;i++){ Student s=(Student)obj[i]; System.out.println(s.getName()+"---"+s.getAge()); } System.out.println("==============================================="); // b: Iterator traversal: Iterator iterator = list.iterator(); while(iterator.hasNext()){ Student s=(Student)iterator.next(); System.out.println(s.getName()+"---"+s.getAge()); } System.out.println("==============================================="); // c:size() is used in conjunction with the get() method for(int i=0;i< list.size();i++){ Student s=(Student)list.get(i); System.out.println(s.getName()+"---"+s.getAge()); } } }
Output result:
Now there is a requirement: there is a set in which some string elements are stored. I want to judge whether there is a string "bigdata". If so, we will add a "yes".
According to what we have learned above, we can use Iterator iterator to traverse:
But in fact, when we use iterator to traverse, we will report an error:
Concurrent modificationexception: concurrent modification exception. When such modification is not allowed, java detects that the object has concurrent modification exception.
reason:
The iterator depends on the set. When traversing the elements in the iterator, when we judge that it is successful, we add an element to the set. However, at this time, the iterator does not know that the element has been added, so the iterator remains unchanged, but at this time, the elements of the iterator are inconsistent with the set, so an error is reported.
Simple description: during iterator traversal, you cannot modify elements through collections
Solution: iterator traversal, iterator modification; Set traversal
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class ListDemo6 { public static void main(String[] args) { //1. Create a collection object List list = new ArrayList(); //2. Add elements to the collection list.add("hello"); list.add("world"); list.add("java"); list.add("bigdata"); list.add("hive"); //ergodic // Iterator iterator = list.iterator(); // while (iterator.hasNext()){ // Object next = iterator.next(); // String s = (String) next; // if("bigdata".equals(s)){ // list.add("yes"); // } // } // Here are two solutions: //Iterator traversal, iterator modification // ListIterator listIterator = list.listIterator(); // while (listIterator.hasNext()){ // Object next = listIterator.next(); // String s = (String) next; // if("bigdata".equals(s)){ // listIterator.add("yes"); // Add after bigdata because the pointer is right here // } // } //Set traversal for(int i=0;i<list.size();i++){ String s = (String) list.get(i); if("bigdata".equals(s)){ list.add("yes"); //Add at the end of the collection } } System.out.println(list); } }
Output results: two output results:
Iterator traverses the output result: yes is added at the current cursor position
Output result of collection traversal: yes is added at the end