Java - Collection, Generics

Articles Catalogue

[Collection, Generics]

primary coverage

  • Collection set
  • iterator
  • Enhanced for
  • generic paradigm

Teaching objectives

  • Ability to tell the difference between sets and arrays
  • Name Common Functions of Collection Sets
  • Ability to use iterators to extract elements from collections
  • Ability to specify the details of the use of collections
  • Ability to store custom types using collections
  • Ability to traverse collections using foreach loops
  • Ability to define collection objects using generics
  • Understanding Generic upper and lower bounds
  • Capable of explaining the role of generic wildcards

Chapter 1 Collection Sets

Overview of 1.1 Collections

We have learned and used the set ArrayList in the previous basic class, so what exactly is the set?

  • Collection: A collection is a container provided in java that can be used to store multiple data.

Since collections and arrays are containers, what's the difference between them?

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

1.2 Collection Framework

JAVASE provides APIs to meet various requirements. Before using these APIs, we need to understand their inheritance and interface operation architecture, so as to know when to adopt which classes and how to cooperate with each other, so as to achieve flexible application.

Collections can be divided into two categories according to their storage structure: single-column set java.util.Collection and double-column set java.util.Map. Today we mainly study Collection collection and explain it at day04.

  • Collection: The root interface of a single column collection class, which stores a series of elements that conform to certain rules, has two important sub-interfaces: java.util.List and java.util.Set. Among them, List is characterized by orderly elements and repeatable elements. Set is characterized by disorder of elements and non-repeatability. The main implementation classes of List interface are java.util.ArrayList and java.util.LinkedList. The main implementation classes of Set interface are java.util.HashSet and java.util.TreeSet.

From the above description, we can see that JDK provides a wealth of collection class libraries. In order to facilitate beginners to learn systematically, the inheritance system of the whole collection class is described by a graph.

[External Link Picture Transfer Failure (img-6DU2Lkzu-1568011412877) (img Collection Set System Diagram. png)]

Among them, the orange box fills in the interface type, while the blue box fills in the specific implementation class. These days we will explain the set classes listed in the figure one by one.

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

1.3 Collection Common Functions

Collection is the parent interface of all single-column collections, so some common methods of single-column collections (List and Set) are defined in Collection, which can be used to manipulate all single-column collections. The methods are as follows:

  • Public Boolean add (E): Adds a given object to the current collection.
  • public void clear(): Clears all elements in the collection.
  • Public Boolean remove (E): Delete a given object from the current collection.
  • Public Boolean contains (E): Determines whether a given object is included in the current collection.
  • 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 elements in a collection into an array.

Method demonstration:

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

public class Demo1Collection {
    public static void main(String[] args) {
		// Creating Collection Objects 
    	// Using polymorphism
    	Collection<String> coll = new ArrayList<String>();
    	// Usage method
    	// Add function Boolean add (String s)
    	coll.add("Little Li Guang");
    	coll.add("Sweeping monk");
    	coll.add("Stone breaks the sky");
    	System.out.println(coll);

    	// Boolean contains (E) determines whether o exists in a set
    	System.out.println("Judging whether the sweeper monk is in the assembly"+coll.contains("Sweeping monk"));

    	//Boolean remove (E) deletes o elements in a collection
    	System.out.println("Delete the stone to break the sky:"+coll.remove("Stone breaks the sky"));
    	System.out.println("Elements in the collection after operation:"+coll);
    	
    	// There are several elements in the size() set
		System.out.println("There are"+coll.size()+"Elements");

		// Object[] toArray() converts to an Object array
    	Object[] objects = coll.toArray();
    	// foreach
    	for (int i = 0; i < objects.length; i++) {
			System.out.println(objects[i]);
		}

		// Void clear () empty collection
		coll.clear();
		System.out.println("The contents of the collection are:"+coll);
		// Boolean isEmpty () to determine whether it is empty
		System.out.println(coll.isEmpty());  	
	}
}

tips: There are more methods in Collection than those mentioned above. Other methods can view API learning by themselves.

Chapter 2 Iterator Iterator Iterator Iterator

2.1 Iterator interface

In program development, it is often necessary to traverse all elements in a collection. To meet this requirement, JDK provides an interface, java.util.Iterator. Iterator interface is also a member of Java collection, but it is different from Collection and Map interface. Collection interface and Map interface are mainly used to store elements, while Iterator is mainly used to iterate over elements in Collection, so Iterator object is also called iterator.

If you want to traverse a Collection collection, you need to get the iterator of the collection to complete the iteration operation. 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.

The following is an introduction to the concept of iteration:

  • Iteration: A common way to get Collection collection elements. Before extracting elements, we should first determine whether there are elements in the set. If there are, we should take this element out and continue to judge. If there are still elements, we should take it out again. All elements in the collection are always taken out. This method of extraction is termed iteration.

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 elements that can be iterated over.

Next, we learn how to use the elements in Iterator iteration set through a case study.

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

        // Add elements to collections
        coll.add("Strings of Aliens");
        coll.add("love remains");
        coll.add("Dog");
        //ergodic
        //Using iterators to traverse each collection object has its own iterator
        Iterator<String> it = coll.iterator();
        //  Generics refer to data types that iterate out elements
        while(it.hasNext()){ //Determine whether there are iteration elements
            String s = it.next();//Get the iterated elements
            System.out.println(s);
        }
  	}
}

tips:: When collecting elements, if there are no elements in the collection and continue to use the next method of iterator, there will be no errors of collecting elements in java.util.NoSuchElementException.

Realization Principle of 2.2 Iterator

We have completed the whole process of Iterator traversing the collection in the previous case. When traversing a set, the iterator object is first obtained by calling iterator() method of t set, and then hashNext() method is used to determine whether the next element exists in the set. If it exists, the next() method is called to extract the element. Otherwise, it means that the iterator has reached the end of the set and stops traversing the element.

Iterator Iterator Iterator Iterator Iterator Iterator Iterator object traverses the set, using a pointer to track the elements in the set. In order to enable beginners to better understand the working principle of Iterator Iterator Iterator Iterator Iterator Iterator object Iterator Iterator Iterator Iterator object Iterator Iterator Iterator Iterator

[External link picture transfer failure (img-GgkqbXCv-1568011412879)(img iterator schematic diagram. bmp)]

Before calling the next method of Iterator, the index of the iterator is located before 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 the element. When the next method is called again, the index of the iterator will point to the first element. Return to the second element, and so on, until the hasNext method returns false, indicating that it reaches the end of the collection and stops traversing the element.

2.3 Enhancement for

Enhanced for loops (also known as for each loops) are advanced for loops that came out after JDK 1.5 and are designed to traverse arrays and collections. Its internal principle is actually an Iterator iterator, so in the process of traversal, the elements in the set can not be added or deleted.

Format:

For (element data type variables: Collection collection or array){ 
  	// Write operation code
}

It is used to traverse collections and arrays. Usually only traversal elements, do not add or delete elements in the process of traversal.

Exercise 1: Traversing arrays

public class NBForDemo1 {
    public static void main(String[] args) {
		int[] arr = {3,5,6,87};
       	//Use enhanced for traversal arrays
		for(int a : arr){//a represents each element in an array
			System.out.println(a);
		}
	}
}

Exercise 2: Traversing Sets

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){//Receiving variable s represents the set element traversed
    		System.out.println(s);
    	}
	}
}

tips: The new for loop must have a traversal target. The target can only be a Collection or an array. The new for only appears as a traversal operation.

Chapter III Generics

Overview of 3.1 Generics

In the previous study of collections, we all know that any object can be stored in the collection, as long as the object is stored in the collection, then they will be promoted to Object type. When we take out each object and do the corresponding operation, we must use type conversion.

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

The program ran with a problem of java.lang.ClassCastException. Why do type conversion exceptions occur? Let's analyze this: because any type of element in a collection can be stored. Causes the ClassCastException to be triggered at runtime when the fetch is forced. How to solve this problem? Collection can store all kinds of objects, but in fact it usually only stores the same type of objects. For example, they all store string objects. Therefore, after JDK5, a new Generic grammar was added to enable you to specify classes or methods to support generics when designing APIs, so that we can use APIs more concise and get compile-time grammar checks.

  • Generics: Unknown types can be pre-branched in classes or methods.

tips: Generally, when creating an object, the unknown type is determined as a specific type. When no generic type is specified, the default type is Object type.

3.2 Benefits of using generics

The last section just explained the introduction of generics, so what are the benefits of generics?

  • Transferring runtime ClassCastException to compile time becomes compile failure.
  • It avoids the trouble of type forcing.

Experience it 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); / / / When a collection is typed, inconsistent storage types compile errors
        // If the set has specified the specific type of element to store, the iterator will also know the specific type of traversal element when using the iterator.
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = it.next();
            //When you use Iterator < String > to control element types, you don't need to force them. The acquired element is the String type directly.
            System.out.println(str.length());
        }
	}
}

tips: Generics are part of data types, and we think of class names and generic merges as data types.

3.3 Definition and Use of Generics

We use generics extensively in collections, so here's a complete study of generics.

Generics are used to flexibly apply data types to different classes, methods and interfaces. The data type is passed as a parameter.

Define and use classes with generics

Definition format:

Modifier class class name < variable representing generic type > {

For example, the ArrayList collection in the API:

class ArrayList<E>{ 
    public boolean add(E e){ }

    public E get(int index){ }
   	....
}

Use generics: When to determine generics.

Determine generics when creating objects

For example, ArrayList < String > List = new ArrayList < String >();

At this point, the value of variable E is the String type, so our type can be understood as:

class ArrayList<String>{ 
     public boolean add(String e){ }

     public String get(int index){  }
     ...
}

For example, ArrayList < Integer > List = new ArrayList < Integer >();

At this point, the value of variable E is the Integer type, so our type can be understood as:

class ArrayList<Integer> { 
     public boolean add(Integer e) { }

     public Integer get(int index) {  }
     ...
}

Examples of custom generic classes

public class MyGenericClass<MVP> {
	//There is no MVP type, which represents an unknown data type and what type to pass in the future.
	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 with generic type String
         MyGenericClass<String> my = new MyGenericClass<String>();    	
         // Call setMVP
         my.setMVP("Great Beard");
         // Call getMVP
         String mvp = my.getMVP();
         System.out.println(mvp);
         //Create a class generic to Integer
         MyGenericClass<Integer> my2 = new MyGenericClass<Integer>(); 
         my2.setMVP(123);   	  
         Integer mvp2 = my2.getMVP();
    }
}

Methods with generics

Definition format:

Modifier < variable representing generic type > 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;
    }
}

Format: When calling a method, determine the type of generic type

public class GenericMethodDemo {
    public static void main(String[] args) {
        // create object
        MyGenericMethod mm = new MyGenericMethod();
        // Demonstration and method hints
        mm.show("aaa");
        mm.show(123);
        mm.show(12.45);
    }
}

Interfaces with generics

Definition format:

Modifier interface name < variable representing generic type > {

For example,

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

Use format:

1. Determining generic types when defining classes

for example

public class MyImp1 implements MyGenericInterface<String> {
	@Override
    public void add(String e) {
        // Elimination of ____________.
    }

	@Override
	public String getE() {
		return null;
	}
}

At this point, the value of generic E is the String type.

2. Always uncertain about the type of generic type, until the object is created, determine the type of generic type

for example

public class MyImp2<E> implements MyGenericInterface<E> {
	@Override
	public void add(E e) {
       	 // Elimination of ____________.
	}

	@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 using generic classes or interfaces, the generic type is uncertain in the data transferred, which can be represented by wildcards <?>. However, once generic wildcards are used, only common methods in Object classes can be used, and the element's own methods in collections cannot be used.

Basic use of wildcards

Generic wildcards: When you don't know what type to use to receive, you can use???? to denote unknown wildcards.

At this time, only data can be accepted, and data can not 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){}
//? Representatives can accept any type

tips: There is no inheritance relationship Collection list = new ArrayList() for generics; this is wrong.

Advanced Use of Wildcard Characters - Restricted Generics

When you set up generics before, you can actually set them arbitrarily, as long as they are classes. But in JAVA generics, you can specify the upper and lower limits of a generic.

The upper limit of 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 received

For example: now known Object class, String class, Number class, 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);
  
}
// The upper limit of generics: generics at this time? Must be subclasses of Number type or Number type
public static void getElement1(Collection<? extends Number> coll){}
// The lower bound of generics: generics at this point? Must be the parent of Number type or Number type.
public static void getElement2(Collection<? super Number> coll){}

Chapter IV Collective Comprehensive Cases

4.1 Case Introduction

Complete the shuffling and licensing according to the rules of the landlord.
Specific rules:

Use 54 cards to disrupt the order, three players participate in the game, three players alternately touch cards, each 17 cards, the last three cards for the bottom card.

4.2 Case Study

  • Preparatory cards:

    The card can be designed as an Array List, each string being a card.
    Each card is composed of two parts: pattern number. We can use pattern set and digital set nested iteration to complete the assembly of each card.
    Cards are randomly sorted by the shuffle method of Collections class.

  • Licensing

    Designing each person and the bottom card as ArrayList, the last three cards are stored directly in the bottom card, and the remaining cards are dealt in turn by taking three models.

  • Look at cards

    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 card operation
        */
        //1.1 Create a card box to store the face of the card in the future 
        ArrayList<String> pokerBox = new ArrayList<String>();
        //1.2 Create a Colour Collection
        ArrayList<String> colors = new ArrayList<String>();

        //1.3 Creating Digital Sets
        ArrayList<String> numbers = new ArrayList<String>();

        //1.4 Adding elements to colors and digital collections, 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 pattern and combine it with each number to store it in the card box.
        for (String color : colors) {
            //Each color 
            //Traversing the set of numbers
            for(String number : numbers){
                //Combination
                String card = color+number;
                //Store in card boxes
                pokerBox.add(card);
            }
        }
        //1.6 Kings and Xiaowangs
        pokerBox.add("Small☺");
        pokerBox.add("large☠");	  
        // System.out.println(pokerBox);
        //Does shuffling mean disrupting the index of the cards in the card box? 
        // Collections class tool classes are static methods
        // shuffer method   
        /*
         * static void shuffle(List<?> list) 
         *     Use the default random source to permute the specified list. 
         */
        //2: shuffling
        Collections.shuffle(pokerBox);
        //3 licensing
        //3.1 Create three players to create a deck set
        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 card boxes   
        for(int i = 0;i<pokerBox.size();i++){
            //Get the face
            String card = pokerBox.get(i);
            //Set aside three cards and store them in the collection of cards.
            if(i>=51){//Save in the Deep Card Collection
                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("Luzhuweng:"+player3);
        System.out.println("A hand:"+dipai);  
	}
}

Keywords: Java JDK

Added by gsv2com on Mon, 09 Sep 2019 10:19:52 +0300