Overview of the Java Collection Framework
On the one hand, object-oriented languages represent things in the form of objects. In order to facilitate the operation of multiple objects, objects need to be stored.On the other hand, there are drawbacks to using Array to store objects, while Java collections are like containers that dynamically place references to multiple objects in containers.
The characteristics of arrays in memory storage:
- After the array is initialized, the length is determined.
- The type of array declaration determines the type of element initialization
Arrays have drawbacks in storing data:
- Once the array is initialized, the length is immutable and not easy to expand
- Arrays provide few attributes and methods, are not easy to add, delete, insert, and other operations, and are not efficient.
- Cannot get the number of storage elements directly at the same time
- Arrays store data that is ordered and repeatable.---->Storing data has a single feature
Java collection classes can be used to store multiple objects of varying number, as well as associated arrays with mapping relationships.
Differences between sets and arrays
- The length of the array is fixed.The length of the collection is variable.
- Arrays store elements of the same type that can store values of the underlying data type.Collections store objects.And the types of objects can be inconsistent.In development, collections are generally used for storage when there are many objects.
Objectives of the learning set
- Stores data using collections
- It traverses the collection and pulls out the data
- Master the characteristics of each set
How to learn sets
- Learning Top Level: A way to learn top level interface/abstract class commonalities, all subclasses can be used
- Use the bottom level: The top level is either an abstract class or an interface and cannot be used to create objects.We're going to use the underlying implementation class to create object usage.'
- Collection interface: A single column of data that defines a collection List of methods for accessing a set of objects: an ordered, repeatable collection Set of elements: an ordered, non-repeatable collection of elements
- Map interface: Two-column data that holds a collection of key-value pairs with a mapping relationship
Collection interface inheritance tree
Map Interface Inheritance Tree
Collection interface
- The Collection interface is the parent of the List, Set, and Queue interfaces, and the methods defined in the interface can be used to manipulate both the Set and Queue collections.
- JDK does not provide any direct implementation of this interface, but rather provides more specific subinterface implementations such as Set and List.
- Prior to Java 5, Java collections lost the data types of all objects in the container, treating all objects as Object types; after adding generics from JDK 5.0, Java collections can remember the data types of objects in the container.
Collection interface method
1. Add
- add(Object obj)
- addAll(Collection coll)
2. Get the number of valid elements
- int size()
3. Empty Collection
- void clear()
4. Is it an empty collection
- boolean isEmpty()
Give an example:
package CollenctionTest; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Date; public class Demo01Collection { @Test public void methodTest() { //polymorphic Collection coll = new ArrayList(); //add(Object e): Add element E to the collection coll coll.add("AA"); coll.add("BB"); coll.add(123);//Automatic packing coll.add(new Date()); //size(): Gets the number of elements added System.out.println(coll.size());//4 //addAll(Collection coll1): Adds elements from the parameter collection to the current collection Collection coll1 = new ArrayList(); coll1.add(456); coll1.add("CC"); coll.addAll(coll1); System.out.println(coll.size());//6 System.out.println(coll);//[AA, BB, 123, Fri Mar 13 02:44:35 CST 2020, 456, CC] //clear(): Empty the collection element coll.clear(); //isEmpty(): Determines if the current collection is empty System.out.println(coll.isEmpty());//true } }
5. Include an element or not
- boolean contains(Object obj): Determines whether the same object is the same by the equals method of the element
- boolean containsAll(Collection c): is also compared by calling the equals method of the element.Compare elements of two sets one by one
6. Delete
- boolean remove(Object obj): Determine if the element is to be deleted by the equals method of the element.Only the first element found will be deleted
- boolean removeAll(Collection coll): Take the difference of the current set
Give an example:
@Test public void methodTest1() { Collection coll = new ArrayList(); /* 1.contains(Object obj):Determine if obj is included in the current collection We call equals() of the class in which the obj object resides when we make a judgment. Adding data obj to an object of an implementation class of the Collection interface requires that the class in which obj resides override equals(). */ coll.add(1); coll.add(new String("a")); coll.add(123); System.out.println(coll.contains("a"));//true //2.containsAll(Collection coll1): Determines whether all elements in the formal parameter coll1 exist in the current collection. Collection coll1 = Arrays.asList(123, 4567); System.out.println(coll.containsAll(coll1));//false //3.remove(Object obj): Remove the obj element from the current collection. boolean a = coll.remove("a"); System.out.println(coll);//[1, 123] //4. removeAll(Collection coll1): Difference sets: Remove all elements of coll1 from the current set. coll.removeAll(coll1); System.out.println(coll);//[1] }
7. Take the intersection of two sets
- boolean retainAll(Collection c): Exists the result of the intersection in the current collection, without affecting C
8. Is the collection equal
- boolean equals(Object obj)
Give an example:
@Test public void Test2() { Collection c1 = new ArrayList(); c1.add(123); c1.add(456); c1.add(new String("Tom")); c1.add(false); //5.retainAll(Collection coll1): Intersection: Gets the intersection of the current set and the coll1 set and returns it to the current set Collection c2 = Arrays.asList(123, 456); c1.retainAll(c2); System.out.println(c1);//[123, 456] //6.equals(Object obj): To return true, the elements of both the current set and the parameter set need to be the same. System.out.println(c1.equals(c2));//true }
9. Convert to Object Array
- Object[] toArray()
10. Get the hash value of the collection object
- hashCode()
11. Traversal
- iterator(): Returns an iterator object for collection traversal
Examples:
@Test public void test3() { Collection coll = new ArrayList(); //Add Elements coll.add(123); coll.add(456); coll.add(new String("Tom")); coll.add(false); //7.hashCode(): Returns the hash value of the current object System.out.println(coll.hashCode()); //8. Set - > Array: toArray() Object[] arr = coll.toArray(); //foreach for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } //Extension: Array--->Set: Call the static method asList() of the Arrays class List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"}); System.out.println(list); List arr1 = Arrays.asList(new int[]{123, 456}); System.out.println(arr1.size());//1 List arr2 = Arrays.asList(new Integer[]{123, 456}); System.out.println(arr2.size());//2 //9.iterator(): Returns an instance of the Iterator interface for traversing collection elements.Testing in IteratorTest.java }
Traversing collection elements using the Iterator interface
- The Iterator object is called an iterator (one of the design patterns) and is primarily used to traverse elements in a Collection collection.
- GOF defines an iterator pattern as providing a way to access the elements of a container object without exposing its internal details.The iterator pattern is created for containers.*
- The Collection interface inherits the java.lang.Iterable interface, which has an iterator() method, and all collection classes that implement the Collection interface have an iterator() method that returns an object that implements the Iterator interface.
- Iterator is only used to traverse collections, and Iterator itself does not provide the ability to load objects.If you need to create an Iterator object, you must have a collection that is iterated over.
- Each time an iterator() method is called by a collection object, a new iterator object is obtained, with the default cursor preceding the first element of the collection.
Here's how to get an iterator:
- public Iterator iterator(): Gets the iterator corresponding to the collection used to iterate through the elements in the collection.
The following describes the concept of iteration:
- Iteration: A common way to get Collection collection elements.Before you take an element, you must first determine if there is an element in the collection. If there is one, you can take it out, continue to make a judgement, and then take it out if there is one.Always take out all the elements in the collection.This method of removal is termed iteration.
Common methods for the Iterator interface are as follows:
- public E next(): Returns the next element of the iteration.
- public boolean hasNext(): Returns true if there are still elements that can be iterated over.
Steps to use the iterator (emphasis):
- Get the implementation class object of the iterator using the method iterator() in the set, and receive (polymorphic) using the Iterator interface
- Use the method hasNext in the Iterator interface to determine if there is another element
- Remove the next element in the collection using the method next in the Iterator interface
Next, we'll use a case study to learn how to use Iterator to iterate over elements in a set:
package demo02; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /* java.util.Iterator Interface: Iterator (traversing a collection) There are two commonly used methods boolean hasNext() Returns true if there are still elements that can be iterated over. Determines if there is another element in the set, returns true if there is one, and false if there is none E next() Returns the next element of the iteration. Remove the next element from the collection Iterator Iterator is an interface that we can't use directly. We need to use Iterator interface to implement class object. The way to get the implementation class is special Collection There is a method in the interface called iterator(), which returns the implementation class object of the iterator Iterator<E> iterator() Returns an iterator that iterates over the elements of this collection. Steps to use the iterator (emphasis): 1.Get the implementation class object of the iterator using the method iterator() in the set, and receive (polymorphic) using the Iterator interface 2.Use the method hasNext in the Iterator interface to determine if there is another element 3.Remove the next element in the collection using the method next in the Iterator interface */ public class Demo01Iterator { public static void main(String[] args) { //Create a collection object Collection<String> coll = new ArrayList<>(); //Add elements to a collection coll.add("Yao Ming"); coll.add("Kobe"); coll.add("McDi"); coll.add("James"); coll.add("Everson"); /* 1.Get the implementation class object of the iterator using the method iterator() in the set, and receive (polymorphic) using the Iterator interface Be careful: Iterator<E>Interfaces are also generic, the generics of iterators follow the set, what is the generic of the set, what is the generic of the iterator */ //Polymorphic Interface Implements Class Objects Iterator<String> it = coll.iterator(); //2. Use the method hasNext in the Iterator interface to determine if there is another element while(it.hasNext()){ //3. Use the method next in the Iterator interface to take out the next element in the collection String e = it.next(); System.out.println(e); } System.out.println("----------------------"); //Format traversal element for loop for(Iterator<String> it2 = coll.iterator();it2.hasNext();){ String e = it2.next(); System.out.println(e); } } }
Be careful:
- If you continue to use the next method of the iterator while collecting elements, there will be an error that java.util.NoSuchElementException does not have collection elements.
Principle of Iterator Implementation
We have completed the Iterator traversal through the collection in the previous case.When traversing a set, first obtain the iterator object by calling the iterator() method of the t set, then use the hashNext() method to determine if the next element exists in the set, and if so, call the next() method to remove the element, otherwise it means that the end of the set has been reached, stopping traversing the element.Iterator iterator objects track elements in a collection internally by pointers as they traverse the collection. To help beginners better understand how the iterator works, the next step is to demonstrate the Iterator object iteration process through a legend:
Before calling the next method of Iterator, the index of the iterator precedes the first element and does not point to any element. When the next method of the iterator is called for the first time, the index of the iterator moves one bit backwards, points to the first element and returns that element. When the next method is called again, the index of the iterator points to the second element and returns that element.By analogy, until the hasNext method returns false, it means the end of the collection has been reached and the element traversal is terminated.
Note:
- Iterator can delete elements of a collection, but it is the remove method of the iterator object during traversal, not the remove method of the collection object.
- If next() has not been called or if the remove method has been called since the last call to the next method, then calling remove will report IllegalStateException.
Examples:
package CollenctionTest; package com.atguigu.java; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * Traversal of collection elements using the iterator Iterator interface * 1.Internal methods: hasNext() and next() * 2.Each time a collection object calls the iterator() method, it gets a completely new iterator object. * The default cursors precede the first element of the collection. * 3.remove() is defined internally to delete elements in a collection while traversing.This method is different from calling remove () directly from a collection * */ public class IteratorTest { //Test remove() in Iterator //If next() has not been called or if the remove method has been called since the last time the next method was called, // Re-calling remove will report IllegalStateException. @Test public void test3() { Collection coll = new ArrayList(); coll.add(123); coll.add(456); coll.add(new String("Tom")); coll.add(false); //Delete "Tom" from collection Iterator iterator = coll.iterator(); while (iterator.hasNext()) { // iterator.remove(); error Object obj = iterator.next(); if ("Tom".equals(obj)) { iterator.remove(); // iterator.remove(); error } } //Traversing through a collection, the collection object gets a completely new iterator object each time it calls the iterator() method. iterator = coll.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Traversing collection elements using a foreach loop
- Java 5.0 provides foreach loop iteration access to Collection s and arrays.
- Traversal does not need to get the length of a Collection or array, nor does it need to use an index to access elements.
- Iterator is called at the bottom of traversing the collection to complete the operation.
- foreach can also be used to traverse arrays.*
- Implement public interface Iterable <T>Implement this interface to allow objects to be the target of a'foreach'statement.Collection<E>extends Iterable<E>: Enhanced for can be used for all single-column collections
Format:
It is used to traverse collections and arrays.Normally only traverse elements, do not add or delete Collection elements during traversal
Code examples
package CollenctionTest; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; public class ForTest { @Test public void test1() { Collection coll = new ArrayList(); coll.add(123); coll.add(456); coll.add(new String("Tom")); coll.add(false); //For (type local variable of collection element: collection object) //The iterator is still called internally. for (Object obj : coll) { System.out.println(obj); } } @Test public void test2() { int[] arr = new int[]{1, 2, 3, 4, 5, 6}; //For (type local variable of array element: array object) for (int i : arr) { System.out.println(i); } } //Exercises @Test public void test3() { String[] arr1 = new String[]{"MM"}; //Mode 1: Ordinary for assignment for (int i = 0; i < arr1.length; i++) { arr1[i] = "GG"; } for (int i = 0; i < arr1.length; i++) { System.out.println(arr1[i]);//GG } String[] arr2 = new String[]{"MM"}; //Mode 2: Enhance for cycle for (String s : arr2) { s = "GG"; } for (int i = 0; i < arr2.length; i++) { System.out.println(arr2[i]);//MM } } }