[Collection, generic type]
primary coverage
- Collection collection
- iterator
- Enhanced for
- generic paradigm
Chapter 1 Collection
1.1 collection overview
In the previous basic class, we have learned and used the set ArrayList, so what is the set?
- Collection: a collection is a container provided in java, which can be used to store multiple data.
Since both sets and arrays are containers, what's the difference between them?
- The length of the array is fixed. The length of the set is variable.
- The elements of the same type are stored in the array, and the basic data type values can be stored. Collections store objects. And the types of objects can be inconsistent. In development, when there are many objects, the collection is used for storage.
1.2 collection framework
Java provides APIs to meet various needs. Before using these APIs, you should first understand their inheritance and interface operation architecture, so as to know when to adopt which class and how to cooperate with each other, so as to achieve flexible application.
According to its storage structure, collections can be divided into two categories: single column collections and Java util. Collection and double column collection Java util. Map, today we mainly study the collection collection and explain the map collection on day04.
- Collection: the root interface of a single column collection class, which is used to store a series of elements that conform to certain rules. It has two important sub interfaces, namely Java util. List and Java util. Set. Among them, list is characterized by ordered elements and repeatable elements. Set is characterized by disordered elements and non repeatable. The main implementation classes of the list interface are Java util. ArrayList and Java util. The main implementation classes of LinkedList and set interfaces are Java util. HashSet and Java util. TreeSet.
From the above description, it can be seen that JDK provides a rich collection class library. In order to facilitate beginners to learn systematically, next, a diagram is used to describe the inheritance system of the whole collection class.
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-rmek0xae-164429753581) (IMG \ collection collection collection system diagram. png)]
Among them, the orange box is filled with interface types, while the blue box is filled with specific implementation classes. The collection classes listed in the figure will be explained one by one in these days.
The Collection itself is a tool, which is stored in Java Util package. The Collection interface defines the most common content in the single column Collection framework.
1.3 common functions of collection
Collection is the parent interface of all single column collections. Therefore, some common methods of single column collections (List and Set) are defined in collection, which can be used to operate all single column collections. The method is as follows:
- Public Boolean add (E): adds the given object to the current collection.
- public void clear(): clear all elements in the collection.
- Public Boolean remove (E): deletes the given object from the current collection.
- Public Boolean contains (E): judge whether the current collection contains the given object.
- public boolean isEmpty(): judge whether the current collection is empty.
- public int size(): returns the number of elements in the collection.
- public Object[] toArray(): store the elements in the collection into the array.
Method demonstration:
import java.util.ArrayList; import java.util.Collection; public class Demo1Collection { public static void main(String[] args) { // Create collection object // Use polymorphic forms Collection<String> coll = new ArrayList<String>(); // usage method // Add function Boolean add (string s) coll.add("Xiao Li Guang"); coll.add("Sweeping monk"); coll.add("Stone breaks the sky"); System.out.println(coll); // boolean contains(E e) determines whether o exists in the set System.out.println("Judge whether the sweeping monk is in the collection"+coll.contains("Sweeping monk")); //Boolean remove (E) deletes the o element in the collection System.out.println("Delete stone breaking sky:"+coll.remove("Stone breaks the sky")); System.out.println("Elements in the collection after the operation:"+coll); // There are several elements in the size() collection System.out.println("There are in the collection"+coll.size()+"Elements"); // Object[] toArray() is converted to an object array Object[] objects = coll.toArray(); // Traversal array for (int i = 0; i < objects.length; i++) { System.out.println(objects[i]); } // Void clear() clears the collection coll.clear(); System.out.println("The contents in the collection are:"+coll); // Boolean isempty() determines whether it is empty System.out.println(coll.isEmpty()); } }
tips: there are more than the above methods in the Collection. Other methods can view the API and learn by themselves.
Chapter 2 Iterator iterator
2.1 Iterator interface
In program development, it is often necessary to traverse all elements in the set. To meet this demand, JDK provides an interface java util. Iterator. The iterator interface is also a member of the Java Collection, but it is different from the Collection and Map interfaces. The Collection interface and Map interface are mainly used to store elements, while the iterator is mainly used to iteratively access (i.e. traverse) the elements in the Collection. Therefore, the iterator object is also called an iterator.
To traverse the Collection, you need to obtain the iterator of the Collection to complete the iterative operation. The following describes the method of obtaining the iterator:
- public Iterator iterator(): get the iterator corresponding to the collection and use it to traverse the elements in the collection.
Here is the concept of iteration:
- Iteration: the general acquisition method of Collection elements. Before taking elements, first judge whether there are elements in the set. If there are, take out this element and continue to judge. If there are any, take it out again. Always take out all the elements in the set. This extraction method is called iteration in technical terms.
The common methods of 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.
Next, let's learn how to use the Iterator to iterate over the elements in the collection through a case:
public class IteratorDemo { public static void main(String[] args) { // Create objects using polymorphism Collection<String> coll = new ArrayList<String>(); // Add element to collection coll.add("String of stars"); coll.add("love remains"); coll.add("dog"); //ergodic //Iterators are used to traverse each collection object, and each collection object has its own iterator Iterator<String> it = coll.iterator(); // Generics are data types that iterate over elements while(it.hasNext()){ //Determine whether there are iterative elements String s = it.next();//Get the iterated element System.out.println(s); } } }
tips:: if you continue to use the next method of the iterator when fetching the collection elements, Java. Net will occur util. NoSuchElementException error without collection element.
2.2 implementation principle of iterator
We have completed the whole process of Iterator traversing the collection in the previous case. When traversing the set, first obtain the Iterator object by calling the iterator() method of the t set, and then use the hashNext() method to judge whether there is the next element in the set. If so, call the next() method to take out the element. Otherwise, it indicates that the end of the set has been reached, and stop traversing the element.
When Iterator iterator object traverses the set, it internally uses pointer to track the elements in the set. In order to enable beginners to better understand the working principle of Iterator, next, a legend is used to demonstrate the iterative process of Iterator object elements:
Before calling the next method of the Iterator, the index of the Iterator is located before the first element and does not point to any element. After calling the next method of the Iterator for the first time, the index of the Iterator will move backward one bit, point to the first element and return the element. When calling the next method again, the index of the Iterator will point to the second element and return the element, And so on, until the hasNext method returns false, which means that the end of the collection is reached and the traversal of the element is terminated.
2.3 enhanced for
The enhanced for loop (also known as the for each loop) is jdk1 5 later, a high-level for loop is specially used to traverse arrays and collections. Its internal principle is actually an Iterator iterator, so in the process of traversal, you can't add or delete elements in the collection.
Format:
for(Data type variable of element : Collection aggregate or array){ //Write operation code }
It is used to traverse collections and arrays. Generally, only the elements are traversed. Do not add or delete the Collection elements in the process of traversal.
Exercise 1: traversing an array
public class NBForDemo1 { public static void main(String[] args) { int[] arr = {3,5,6,87}; //Using enhanced for traversal arrays for(int a : arr){//a represents each element in the array System.out.println(a); } } }
Exercise 2: traversing a collection
public class NBFor { public static void main(String[] args) { Collection<String> coll = new ArrayList<String>(); coll.add("River god"); coll.add("Old river god"); coll.add("God woman"); //Using enhanced for traversal for(String s :coll){//The received variable s represents the traversed set element System.out.println(s); } } }
tips: the new for loop must have a target to be traversed. The target can only be a Collection or an array. The new for only appears as a traversal operation.
Chapter 3 generics
3.1 generic overview
When we learned about the collection, we all know that any Object can be stored in the collection. As long as the objects are stored in the collection, they will be promoted to Object type. When we take out each Object and perform corresponding operations, we must use type conversion.
Look at the following code:
public class GenericDemo { public static void main(String[] args) { Collection coll = new ArrayList(); coll.add("abc"); coll.add("itcast"); coll.add(5);//Since the collection has no restrictions, any type can be stored in it Iterator it = coll.iterator(); while(it.hasNext()){ //To print the length of each String, you need to convert the iterated object into String type String str = (String) it.next(); System.out.println(str.length()); } } }
A problem occurred while the program was running lang.ClassCastException. Why do type conversions occur? Let's analyze: because any type of element in the Collection can be stored. This will cause the forced rotation on fetch to cause the runtime ClassCastException. How to solve this problem? Although a Collection can store various objects, in fact, a Collection usually only stores objects of the same type. For example, they are all stored string objects. Therefore, after JDK5, generic syntax is added, so that you can specify classes or methods to support generics when designing the API. In this way, when we use the API, it becomes more concise and gets syntax check during compilation.
- Generics: unknown types can be used in advance in classes or methods.
tips: generally, when creating an Object, the unknown type is determined as the specific type. When no generic type is specified, the default type is Object type.
3.2 benefits of using generics
The previous section only explained the introduction of generics, so what benefits does generics bring?
- When the ClassCastException of the runtime is transferred to the compilation time, it becomes a compilation failure.
- Avoid the trouble of type forced conversion.
Let's experience it through the following code:
public class GenericDemo2 { public static void main(String[] args) { Collection<String> list = new ArrayList<String>(); list.add("abc"); list.add("itcast"); // list.add(5);// When the type of the collection is specified, if the storage types are inconsistent, the compilation will report an error // The collection has specified the specific element type, so when using the iterator, the iterator will also know the specific traversal element type Iterator<String> it = list.iterator(); while(it.hasNext()){ String str = it.next(); //When you use iterator < String > to control the element type, you don't need to force conversion. The obtained element is directly of String type System.out.println(str.length()); } } }
tips: generics are part of data types. We combine class names and generics as data types.
3.3 definition and use of generics
We will make extensive use of generics in the collection. Here we can learn the knowledge of generics completely.
Generics are used to flexibly apply data types to different classes, methods and interfaces. Pass the data type as a parameter.
Define and use classes with generics
Define format:
Modifier class Class name<Variables representing generics> { }
For example, the ArrayList collection in the API:
class ArrayList<E>{ public boolean add(E e){ } public E get(int index){ } .... }
Use generics: that is, when to determine generics.
Determine generics when creating objects
For example, ArrayList < string > List = new ArrayList < string > ();
At this time, the value of variable E is String type, so our type can be understood as:
class ArrayList<String>{ public boolean add(String e){ } public String get(int index){ } ... }
For another example, ArrayList < integer > List = new ArrayList < integer > ();
At this time, the value of variable E is Integer type, so our type can be understood as:
class ArrayList<Integer> { public boolean add(Integer e) { } public Integer get(int index) { } ... }
Examples: Custom generic classes
public class MyGenericClass<MVP> { //There is no MVP type. Here, it represents an unknown data type. What will be passed in the future is what type private MVP mvp; public void setMVP(MVP mvp) { this.mvp = mvp; } public MVP getMVP() { return mvp; } }
use:
public class GenericClassDemo { public static void main(String[] args) { // Create a class whose generic type is String MyGenericClass<String> my = new MyGenericClass<String>(); // Call setMVP my.setMVP("Big beard Deng"); // Call getMVP String mvp = my.getMVP(); System.out.println(mvp); //Create a class whose generic type is Integer MyGenericClass<Integer> my2 = new MyGenericClass<Integer>(); my2.setMVP(123); Integer mvp2 = my2.getMVP(); } }
Methods with generics
Define format:
Modifier <Variables representing generics> Return value type method name(parameter){ }
For example,
public class MyGenericMethod { public <MVP> void show(MVP mvp) { System.out.println(mvp.getClass()); } public <MVP> MVP show2(MVP mvp) { return mvp; } }
Use format: determines the type of generic type when calling a method
public class GenericMethodDemo { public static void main(String[] args) { // create object MyGenericMethod mm = new MyGenericMethod(); // Show me how to see Tips mm.show("aaa"); mm.show(123); mm.show(12.45); } }
Interface with generics
Define format:
Modifier interface Interface name<Generic representation of variables> { }
For example,
public interface MyGenericInterface<E>{ public abstract void add(E e); public abstract E getE(); }
Use format:
1. Determine the type of generic type when defining a class
For example:
public class MyImp1 implements MyGenericInterface<String> { @Override public void add(String e) { // Omit } @Override public String getE() { return null; } }
At this point, the value of generic E is of type String.
2. The type of generics is always uncertain until the type of generics is determined when the object is created
for example
public class MyImp2<E> implements MyGenericInterface<E> { @Override public void add(E e) { // Omit } @Override public E getE() { return null; } }
Determine generics:
/* * use */ public class GenericInterface { public static void main(String[] args) { MyImp2<String> my = new MyImp2<String>(); my.add("aa"); } }
3.4 generic wildcards
When a generic class or interface is used, the generic type in the passed data is uncertain. You can use the wildcard <? > express. However, once the generic wildcard is used, only the common methods in the Object class can be used, and the methods of the elements in the collection cannot be used.
Basic use of wildcards
Generic wildcard: when you don't know what type to use to receive, you can use?,? Indicates an unknown wildcard.
At this time, only data can be accepted, and data cannot be stored in the collection.
For example, you can understand and use it:
public static void main(String[] args) { Collection<Intger> list1 = new ArrayList<Integer>(); getElement(list1); Collection<String> list2 = new ArrayList<String>(); getElement(list2); } public static void getElement(Collection<?> coll){} //? Representative can receive any type
tips: there is no inheritance relationship between generic types. Collection list = new ArrayList(); This is wrong.
Advanced use of wildcards -- restricted generics
When you set generics before, you can actually set them arbitrarily, as long as they are classes. However, in JAVA generics, you can specify the upper and lower limits of a generics.
Upper limit of generics:
- Format: type name <? Extensions class > object name
- Meaning: only this type and its subclasses can be accepted
Lower bound of generics:
- Format: type name <? Super class > object name
- Meaning: only this type and its parent type can be accepted
For example, we now know Object class, String class, Number class and Integer class, where Number is the parent class of Integer
public static void main(String[] args) { Collection<Integer> list1 = new ArrayList<Integer>(); Collection<String> list2 = new ArrayList<String>(); Collection<Number> list3 = new ArrayList<Number>(); Collection<Object> list4 = new ArrayList<Object>(); getElement(list1); getElement(list2);//report errors getElement(list3); getElement(list4);//report errors getElement2(list1);//report errors getElement2(list2);//report errors getElement2(list3); getElement2(list4); } // Upper limit of generics: generics at this time?, Must be of type Number or a subclass of type Number public static void getElement1(Collection<? extends Number> coll){} // Lower limit of generics: generics at this time?, Must be of type Number or a parent of type Number public static void getElement2(Collection<? super Number> coll){}
Chapter IV collection of comprehensive cases
4.1 case introduction
Complete the shuffle and deal according to the rules of fighting the landlord.
Specific rules:
Use 54 cards to disrupt the order, three players participate in the game, three people touch cards alternately, 17 cards for each person, and the last three cards are reserved as bottom cards.
4.2 case analysis
-
Prepare cards:
Cards can be designed as an ArrayList, and each string is a card.
Each card consists of two parts: color and number. We can use the nested iteration of color set and number set to complete the assembly of each card.
Cards are randomly sorted by the shuffle method of the Collections class. -
Licensing
Each person and the cards are designed as ArrayList, the last three cards are directly stored in the cards, and the remaining cards are dealt in turn by taking a mold of 3.
-
Watch cards
Print each set directly.
4.3 code implementation
import java.util.ArrayList; import java.util.Collections; public class Poker { public static void main(String[] args) { /* * 1: Prepare card operation */ //1.1 create a card box to store card faces in the future ArrayList<String> pokerBox = new ArrayList<String>(); //1.2 creating Decor sets ArrayList<String> colors = new ArrayList<String>(); //1.3 creating digital sets ArrayList<String> numbers = new ArrayList<String>(); //1.4 add elements to decors and number sets respectively colors.add("♥"); colors.add("♦"); colors.add("♠"); colors.add("♣"); for(int i = 2;i<=10;i++){ numbers.add(i+""); } numbers.add("J"); numbers.add("Q"); numbers.add("K"); numbers.add("A"); //1.5 creation card splicing operation // Take out each decor and then combine it with each number to store it in the card box for (String color : colors) { //color each Decor //Traversal number set for(String number : numbers){ //combination String card = color+number; //Store in card box pokerBox.add(card); } } //1.6 king and Xiao Wang pokerBox.add("Small☺"); pokerBox.add("large☠"); // System.out.println(pokerBox); //Is shuffling the index of cards in the card box // Collections and tool classes are static methods // Shuffler method /* * static void shuffle(List<?> list) * Replaces the specified list with the default random source. */ //2: Shuffle Collections.shuffle(pokerBox); //3 licensing //3.1 create three player sets and create a set of cards ArrayList<String> player1 = new ArrayList<String>(); ArrayList<String> player2 = new ArrayList<String>(); ArrayList<String> player3 = new ArrayList<String>(); ArrayList<String> dipai = new ArrayList<String>(); //The index must be known when traversing the card box for(int i = 0;i<pokerBox.size();i++){ //Get face String card = pokerBox.get(i); //Set aside three cards and save them in the bottom card set if(i>=51){//Save to the deck set dipai.add(card); } else { //Player 1% 3 = = 0 if(i%3==0){ player1.add(card); }else if(i%3==1){//Player 2 player2.add(card); }else{//Player 3 player3.add(card); } } } //have a look System.out.println("linghu chong:"+player1); System.out.println("Tian boguang:"+player2); System.out.println("Green bamboo Weng:"+player3); System.out.println("a hand:"+dipai); } }