This is the sixth day of my participation in the August Text Challenge.More challenges in August

Content preview

  • The Collection Collection
  • The iterator
  • Enhance the for
  • The generic

The Collection Collection

1.1 Overview of Collections

We’ve already seen and used collections ArrayList in the basics class, so what exactly is a collection?

  • Collections: COLLECTIONS are containers provided in Java that can be used to store multiple pieces of data.

Collections and arrays are containers, so what’s the difference?

  • The length of the array is fixed. The length of the set is variable.
  • Arrays store elements of the same type and can store basic data type values. Collections store objects. And object types can be inconsistent. In development, collections are used for storage when there are many objects.

1.2 Collection Framework

JAVASE provides apis to meet a variety of needs, and before you can use these apis, you need to understand their inheritance and interface architecture to know when to use which classes and how to work with each other for flexible application.

Collection can be divided into two categories according to its storage structure, namely single-column Collection java.util.Collection and double-column Collection java.util.Map. Today we will mainly study Collection Collection and explain Map Collection on Day04.

  • Collection: The root interface of the single-column collection class, used to store a list of elements that conform to a certain rule. It has two important subinterfaces, respectivelyjava.util.Listandjava.util.Set. Among them,ListIs characterized by ordered elements and repeatable elements.SetIs characterized by elements that are unordered and not repeatable.ListThe main implementation classes of interfaces arejava.util.ArrayListandjava.util.LinkedList.SetThe main implementation classes of interfaces arejava.util.HashSetandjava.util.TreeSet.

It can be seen from the above description that the JDK provides a rich collection class library, in order to facilitate beginners to systematically learn, the next through a diagram to describe the entire collection class inheritance system.

The collection itself is a tool that is stored in the java.util package. The Collection interface defines the most common content in the single-column Collection framework.

1.3 Common Collection functions

Collection is the parent interface to all single-column collections, so there are methods common to single-column collections (lists and sets) defined in Collection that can be used to manipulate all single-column collections. The method is as follows:

  • public boolean add(E e): adds the given object to the current collection.
  • public void clear(): Clears all the elements in the collection.
  • public boolean remove(E e): Deletes the given object from the current collection.
  • public boolean contains(E e): Determines whether the current collection contains the given object.
  • public boolean isEmpty(): Determines whether the current collection is empty.
  • public int size(): Returns the number of elements in the collection.
  • public Object[] toArray(): Stores the elements of the collection into an array.

Method demonstration:

import java.util.ArrayList;
import java.util.Collection;

public class Demo1Collection {
    public static void main(String[] args) {
		// Create a collection object
    	// Use polymorphic form
    	Collection<String> coll = new ArrayList<String>();
    	// How to use it
    	Boolean add(String s)
    	coll.add("Xiao Li Guang");
    	coll.add("Sweeping Monk");
    	coll.add("Stone Sky");
    	System.out.println(coll);

    	// Boolean contains(E E) determines whether o exists in the set
    	System.out.println("Determine if the sweeping monk is in the assembly."+coll.contains("Sweeping Monk"));

    	// Boolean remove(E E) removes the o element in the set
    	System.out.println("Delete Stone Sky:"+coll.remove("Stone Sky"));
    	System.out.println("Elements in the set after operation :"+coll);
    	
    	There are several elements in the size() collection
		System.out.println("There is in the set."+coll.size()+"The element");

		// Object[] toArray() converts to an Object array
    	Object[] objects = coll.toArray();
    	// go through the number group
    	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 of the set are:"+coll);
		// Boolean isEmpty() checks whether it isEmptySystem.out.println(coll.isEmpty()); }}Copy the code

Tips: You can learn more about the methods in the Collection by looking at the API.


The Iterator Iterator

2.1 the Iterator interface

In program development, it is often necessary to iterate over all the elements in a collection. For this purpose, the JDK provides an interface called java.util.iterator. The Iterator interface is also a member of the Java Collection. Unlike the Collection and Map interfaces, which store elements, the Iterator interface iterates through the elements of a Collection. Hence Iterator objects are also called iterators.

To iterate over the Collection, we need to get the iterator to complete the iteration. Here’s how to get the iterator:

  • public Iterator iterator(): Gets the iterator corresponding to the collection, which is used to traverse the elements in the collection.

Here is the concept of iteration:

  • Iteration: A generic way to get elements of a Collection. Before you take an element, you have to check if there is an element in the set, and if there is, you take the element out, and if there is, you take it out again. I keep pulling all the elements out of the set. The technical term for this method of extraction is iteration.

The common methods for Iterator interfaces are as follows:

  • public E next(): returns the next element of the iteration.
  • public boolean hasNext(): Returns true if there are still elements to iterate over.

Let’s take a look at how to use Iterator to iterate over elements in a collection:

public class IteratorDemo {
  	public static void main(String[] args) {
        // Create objects in polymorphic mode
        Collection<String> coll = new ArrayList<String>();

        // Add elements to the collection
        coll.add("Star Men.");
        coll.add("Mocking the Stars.");
        coll.add("Dog People");
        / / traverse
        Each collection object has its own iterator
        Iterator<String> it = coll.iterator();
        // Generics refer to iterating out the data type of the element
        while(it.hasNext()){ // Determine if there are iteration elements
            String s = it.next();// Get the iterated elementSystem.out.println(s); }}}Copy the code

Tips: : when element to set out, if there is no element in the set, still continue to use the iterator next method, Java will happen. Util. NoSuchElementException no error collection elements.

2.2 Implementation principle of iterators

We walked through the entire set of iterators in the previous example. When iterating through the collection, we first get the iterator object by calling the iterator() method of the collection t. Then we use hashNext() to determine whether the next element exists in the collection. If so, we call next() to pull the element out.

Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator

Before calling next, the Iterator’s index precedes the first element and does not refer to any element. After the first call to next, the Iterator’s index moves back one bit to refer to the first element and returns that element. When next is called again, The iterator’s index points to the second element and returns it, and so on, until the hasNext method returns false, indicating that the end of the collection has been reached, terminating the iteration of the element.

2.3 enhance the for

The enhanced for loop (also known as the for each loop) is an advanced for loop developed after JDK1.5 that iterates through groups and collections. It’s an Iterator, so you can’t add or remove elements from the collection.

Format:

for(Element data type variable: Collection Collection or array){// Write the operation code
}
Copy the code

It is used to iterate over collections and arrays. Generally, only elements are iterated; do not add or delete collection elements during the traversal.

Exercise 1: Go through the number sets

public class NBForDemo1 {
    public static void main(String[] args) {
		int[] arr = {3.5.6.87};
       	// Use the for enhancement to iterate over the number group
		for(int a : arr){// A represents each element in the arraySystem.out.println(a); }}}Copy the code

Exercise 2: Iterate over the collection

public class NBFor {
    public static void main(String[] args) {        
    	Collection<String> coll = new ArrayList<String>();
    	coll.add("Little River God");
    	coll.add(Old River God);
    	coll.add("Witch");
    	// Use enhanced for traversal
    	for(String s :coll){// The receiving variable s represents the collection element to be traversedSystem.out.println(s); }}}Copy the code

Tips: New for loops must have a target to be traversed. The target can only be Collection or array. The new for appears only as a traversal operation.


The generic

3.1 Overview of generics

When we learned about collections, we all know that collections can hold any Object. Once objects are stored in collections, they will be promoted to Object type. When we are fetching each object and performing operations, we must use type conversions.

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 is not qualified, any type can be stored in it
		Iterator it = coll.iterator();
		while(it.hasNext()){
			// To print the length of each String, convert the iterated object to StringString str = (String) it.next(); System.out.println(str.length()); }}}Copy the code

Program at runtime problems happened in the Java lang. ClassCastException. Why do cast exceptions occur? Because any type of element in a set can be stored. Causes the load time to strongly redirect the ship time ClassCastException. How to solve this problem? Although a Collection can store a variety of objects, in practice it only stores objects of the same type. For example, both store string objects. So after JDK5, we added Generic syntax, which allows you to specify classes or methods that support generics when you design an API, so that we can use the API more succinctly and get compile-time syntax checks.

  • Generics: You can pre-emptively use unknown types in a class or method.

Tips: When you create an object, you usually define a specific type from an unknown type. When no generics are specified, the default type is Object.

3.2 Benefits of using generics

The last section was just about the introduction of generics, so what benefits do generics bring?

  • Moving the ClassCastException from runtime to compile time becomes compile failure.
  • Avoid the trouble of strong type rotation.

Try it out with 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); // If the set type is not consistent, an error will be reported
        // When the iterator is used, the iterator also knows the element type to be iterated over
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = it.next();
            // When you use Iterator
      
        to control the type of an element, you don't need to force it. The retrieved element is a String
      System.out.println(str.length()); }}}Copy the code

Tips: Generics are part of a data type, and we combine class names with generics as data types.

3.3 Definition and use of generics

We’ll make a lot of use of generics in collections, so learn about generics in their entirety here.

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 that contain generics

Definition format:

Class class name < variables representing generics > {}Copy the code

For example, the ArrayList collection in the API:

class ArrayList<E>{ 
    public boolean add(E e){}public E get(int index){}... }Copy the code

Use generics: that is, when generics are determined.

Determine the generic type when creating the object

For example, ArrayList

list = new ArrayList

();

In this case, the value of variable E is of type String, so our type can be interpreted as:

class ArrayList<String>{ 
     public boolean add(String e){}public String get(int index){}... }Copy the code

For example, ArrayList

list = new ArrayList

();

In this case, the value of variable E is of type Integer, so our type can be interpreted as:

class ArrayList<Integer> { 
     public boolean add(Integer e) {}public Integer get(int index) {}... }Copy the code

Example custom generic classes

public class MyGenericClass<MVP> {
	// There is no MVP type, which represents an unknown data type
	private MVP mvp;
     
    public void setMVP(MVP mvp) {
        this.mvp = mvp;
    }
     
    public MVP getMVP(a) {
        returnmvp; }}Copy the code

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("Dundon the Beard.");
         / / call getMVP
         String mvp = my.getMVP();
         System.out.println(mvp);
         // Create a class with a generic type of Integer
         MyGenericClass<Integer> my2 = new MyGenericClass<Integer>(); 
         my2.setMVP(123); Integer mvp2 = my2.getMVP(); }}Copy the code

Methods that contain generics

Definition format:

Modifier < variables representing generics > return value type method name (parameter){}Copy the code

For example,

public class MyGenericMethod {	  
    public <MVP> void show(MVP mvp) {
    	System.out.println(mvp.getClass());
    }
    
    public <MVP> MVP show2(MVP mvp) {	
    	returnmvp; }}Copy the code

Use format: When calling a method, determine the type of the generic type

public class GenericMethodDemo {
    public static void main(String[] args) {
        // Create an object
        MyGenericMethod mm = new MyGenericMethod();
        // show the method hint
        mm.show("aaa");
        mm.show(123);
        mm.show(12.45); }}Copy the code

Interfaces that contain generics

Definition format:

Interface Interface name < variables representing generics > {}Copy the code

For example,

public interface MyGenericInterface<E>{
	public abstract void add(E e);
	
	public abstract E getE(a);  
}
Copy the code

Use format:

Define the type of the generic when defining the class

For example,

public class MyImp1 implements MyGenericInterface<String> {
	@Override
    public void add(String e) {
        / / to omit...
    }

	@Override
	public String getE(a) {
		return null; }}Copy the code

In this case, the value of the generic E is String.

2. The type of the generic is never determined until the object is created

For example,

public class MyImp2<E> implements MyGenericInterface<E> {
	@Override
	public void add(E e) {
       	 / / to omit...
	}

	@Override
	public E getE(a) {
		return null; }}Copy the code

Determine generics:

/*
 * 使用
 */
public class GenericInterface {
    public static void main(String[] args) {
        MyImp2<String>  my = new MyImp2<String>();  
        my.add("aa"); }}Copy the code

3.4 Generic wildcards

When using generic classes or interfaces, you can pass data in which the generic type is not determined by the wildcard <? > said. But once you use generic wildcards, you can only use the generic methods of the Object class, not the elements in the collection themselves.

The wildcard character is basically used

Generic wildcards: can be used when you do not know what type to use for receiving? ,? Indicates an unknown wildcard.

At this point, only data can be accepted, and data cannot be stored in the collection.

Here’s an example you can understand and use:

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){}
/ /? Indicates that any type can be received
Copy the code

Collection List = new ArrayList(); This is wrong.

Wildcard advanced uses —- restricted generics

When you set generics, you can actually set them as long as they’re classes. But in JAVA generics you can specify the upper and lower limits of a generics.

Upper limits on generics:

  • format:Type name <? Extends class > Object name
  • meaning:Only this type and its subclasses can be accepted

The lower limit 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 the Object class, String class, Number class, and Integer class, where Number is the parent 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);/ / an error
    getElement(list3);
    getElement(list4);/ / an error
  
    getElement2(list1);/ / an error
    getElement2(list2);/ / an error
    getElement2(list3);
    getElement2(list4);
  
}
// The upper limit of generics: the generics at this time? Must be type Number or a subclass of type Number
public static void getElement1(Collection<? extends Number> coll){}
// The lower limit of generics: the generics at this time? Must be type Number or a parent of type Number
public static void getElement2(Collection<? super Number> coll){}
Copy the code

Set synthesis case

4.1 Case Description

According to the rules of doudizhu, complete the shuffling and licensing action. Specific rules:

Using 54 cards to shuffle the order, three players play the game, three people alternately touch cards, 17 cards each, the last three reserved for the bottom card.

4.2 Case Analysis

  • Preparation:

    Cards can be designed as an ArrayList, with one card per string. Each card is composed of two parts of suit and number. We can use suit set and number set nested iteration to complete the assembly of each card. The cards are sorted randomly by the Shuffle method of the Collections class.

  • licensing

    Each person and the bottom card are designed as an ArrayList, and the last three cards are directly stored in the bottom card, and the remaining cards are dealt in turn by taking three modules.

  • See the card

    Print each collection directly.

4.3 Code Implementation

import java.util.ArrayList;
import java.util.Collections;

public class Poker {
    public static void main(String[] args) {
        /* * 1: prepare cards */
        // create a card box to store card faces
        ArrayList<String> pokerBox = new ArrayList<String>();
        // create a suit set
        ArrayList<String> colors = new ArrayList<String>();

        //1.3 Creating a collection of numbers
        ArrayList<String> numbers = new ArrayList<String>();

        //1.4 Add elements to suit and number sets respectively
        colors.add("Has");
        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 Create card splice card operation
        // Take each suit and store it in the card box with each number
        for (String color : colors) {
            //color each color
            // Iterate over the collection of numbers
            for(String number : numbers){
                / / in combination with
                String card = color+number;
                // Store it in the card boxpokerBox.add(card); }}//1.6 King Xiao Wang
        pokerBox.add("Little ☺");
        pokerBox.add("Big ☠");	  
        // System.out.println(pokerBox);
        // Shuffle is to shuffle the index of the cards in the card box
        // The Collections class utility classes are static methods
        / / shuffer method
        /* * static void shuffle(List
        list) * replaces the specified list with the default random source. * /
        / / 2: shuffle
        Collections.shuffle(pokerBox);
        / / 3
        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 a card box
        for(int i = 0; i<pokerBox.size(); i++){// Get the card
            String card = pokerBox.get(i);
            // Save three cards in the deck
            if(i>=51) {// Save to the bottom card 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{//玩家3player3.add(card); }}}/ / look at
        System.out.println(Linghu Chong:+player1);
        System.out.println(Tian Boguang:+player2);
        System.out.println("Green bamboo Weng:"+player3);
        System.out.println("Bottom card:"+dipai); }}Copy the code