[Java foundation] 11 "single column set and generics

Collection collection

Collection overview

In the previous basic class, we have learned and used ArrayList, so what is a collection?

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

Since 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 array stores 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, when there are many objects, the collection is used for storage.

Set framework

Java se provides APIs to meet various requirements. Before using these APIs, you need to understand their inheritance and interface operation architecture, so as to know when to use which class and how to cooperate with each other, so as to achieve 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 mainly study collection collection and explain Map collection on day04.

  • Collection: the root interface of a single column collection class, 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 orderly elements and repeatable elements. Set is characterized by element disorder and non repetition. The main implementation classes of List interface are java.util.ArrayList and java.util.LinkedList, and 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 rich set class library. In order to facilitate the beginners' systematic learning, we will describe the inheritance system of the whole set class through a diagram.

Among them, the orange box is filled with interface types, while the blue box is filled with specific implementation classes. In these days, we will explain the collection 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 the single column Collection framework.

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 operate 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 elements in the collection.
  • public boolean remove(E e): delete the given object in 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(): store the elements in 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 collection object 
    	// Using 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("Shi Tian Tian");

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

    	//Boolean remove (e e e) removes o elements from a collection
    	System.out.println("Delete stone sky:"+coll.remove("Shi Tian Tian"));
    	System.out.println("Elements in collection after operation:"+coll);
    	// There are several elements in the size() collection
		System.out.println("In the collection"+coll.size()+"Element");

		// Object[] toArray() to an object array
    	Object[] objects = coll.toArray();
    	// Traversing array
    	for (int i = 0; i < objects.length; i++) {

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

tips: there are more methods in Collection than the above. Other methods can view API learning by themselves.

Iterator iterator

Iterator interface

In program development, it is often necessary to traverse all elements in a collection. In response to this demand, JDK provides a special 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 (i.e. traverse) elements in collection, so iterator object is also called iterator.

To traverse a Collection collection, you need to obtain the Collection iterator to complete the iteration operation. Here's how to obtain 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: the general way to get Collection elements. Before fetching the elements, you should first judge whether there are elements in the Collection. If there are any, you should take out the elements, continue to judge, and if there are any, you can take them out again. Always take all the elements out of the Collection. The term for this extraction method is 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 still elements that can be iterated.

Next, we learn how to use Iterator to iterate over the elements in the collection through a case study:

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

        // Add element to collection
        coll.add("String stars");
        coll.add("love remains");
        //Using iterators to traverse each collection object has its own iterator
        Iterator<String> it = coll.iterator();
        //  Generics are data types that iterate out elements
        while(it.hasNext()){ //Determine if there are iteration elements
            String s = it.next();//Get iterated elements

tips:: during collection element extraction, if there is no element in the collection and you continue to use the next method of iterator, you will get the error that java.util.NoSuchElementException has no collection element.

The implementation principle of iterator

We have completed the whole process of Iterator traversing the collection in the previous case. When traversing a collection, first obtain the Iterator object by calling the iterator() method of the t collection, and then use the hashNext() method to determine whether the next element exists in the collection. If it exists, then call the next() method to take out the element, otherwise, it means that the end of the collection has been reached, and stop traversing the element.

When Iterator iterator object traverses the collection, it uses pointer to track the elements in the collection. In order to let beginners better understand the working principle of Iterator, next, it uses a legend to demonstrate the process of Iterator object iteration elements:

Before calling the next method of Iterator, the index of Iterator is located before the first element and does not point to any element. When the next method of Iterator is called for the first time, the index of Iterator will move backward one bit, point to the first element and return the element. When the next method is called again, the index of Iterator will point to the second element and return the element, and so on By analogy, until the hasNext method returns false, indicating that the end of the collection is reached and the traversal of the element is terminated.

Enhanced for

Enhanced for loop (also known as for each loop) is an advanced for loop after JDK 1.5, which is specially used to traverse arrays and collections. Its internal principle is actually an Iterator iterator, so in the process of traversal, you cannot add or delete elements in the collection.


For (data type variable of element: Collection collector array){ 
  	//Write operation code

It is used to traverse collections and arrays. Generally, we only need to traverse the elements, and do not add or delete the set 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};
       	//Traversing arrays with enhanced for
		for(int a : arr){//a represents each element in the array

Exercise 2: traversing a set

public class NBFor {
    public static void main(String[] args) {        
    	Collection<String> coll = new ArrayList<String>();
    	coll.add("Creek God");
    	coll.add("Old river god");
    	coll.add("God woman");
    	//Use enhanced for traversal
    	for(String s :coll){//The receive variable s represents the set element traversed

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

generic paradigm

Generic overview

In the previous study of collection, 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 are taking out every Object and doing the corresponding operation, we must adopt the type conversion.

Look at the following code:

public class GenericDemo {
	public static void main(String[] args) {
		Collection coll = new ArrayList();
		coll.add(5);//Since the collection has no restrictions, any type can be stored in it
		Iterator it = coll.iterator();
			//To print the length of each String, you need to convert the iterated object to String type
			String str = (String) it.next();

The program encountered a problem at run time java.lang.ClassCastException. Why do type conversion exceptions occur? Let's analyze: because any type of element in the Collection can be stored. Causes a strong transition on fetch to raise a runtime ClassCastException. How to solve this problem? Although Collection can store various objects, in fact, Collection usually only stores objects of the same type. For example, they are all storage string objects. Therefore, after JDK5, generic syntax has been added, which allows you to specify classes or methods to support generics when designing API. In this way, when we use API, it becomes more concise and gets syntax check at compile time.

  • Generics: unknown types can be used in advance in a class or method.

tips: generally, when creating an Object, the unknown type determines the specific type. When no generics are specified, the default type is Object.

Benefits of using generics

The previous section only explained the introduction of generics, so what are the benefits of generics?

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

Let's experience the following code:

public class GenericDemo2 {
	public static void main(String[] args) {
        Collection<String> list = new ArrayList<String>();
        // list.add(5); / / when the set has a clear type, the storage type is inconsistent, and an error will be reported
        // The collection has specified the type of element to store, so when using the iterator, the iterator will also know the type of traversal element
        Iterator<String> it = list.iterator();
            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 the String type directly

tips: generics are part of data types. We consider class names and generics merging as data types.

The definition and use of generics

We will use generics in a large number of collections. Here we will learn generics completely.

Generics are used to flexibly apply data types to different classes, methods and interfaces. Pass the data type as a parameter.

There are three ways to use generics: generic classes, generic interfaces, and generic methods.

Classes with generics

Generic types are used in the definition of a class and are called generic classes. Through generics, you can open the same interface to a group of classes. The most typical is various container classes, such as List, Set, Map

Definition format:

Modifier class class name < variable representing generic > {}

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 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 of type Integer, so our type can be understood as:

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

     public Integer get(int index) {  }

Example custom generic class

public class MyGenericClass<MVP> {
	//There is no MVP type, which represents an unknown data type. What type will be passed in the future
	private MVP mvp;
    public void setMVP(MVP mvp) {
        this.mvp = mvp;
    public MVP getMVP() {
        return mvp;


public class GenericClassDemo {
  	public static void main(String[] args) {		 
         // Create a class with a generic type of String
         MyGenericClass<String> my = new MyGenericClass<String>();    	
         // Call setMVP
         my.setMVP("Dahuzi dengdeng");
         // Call getMVP
         String mvp = my.getMVP();
         //Create a class whose generics are Integer
         MyGenericClass<Integer> my2 = new MyGenericClass<Integer>(); 
         Integer mvp2 = my2.getMVP();

Methods with generics

Definition format:

Modifier < variable representing generic > return value type method name (parameter) {}

For example,

public class MyGenericMethod {	  
    public <MVP> void show(MVP mvp) {
    public <MVP> MVP show2(MVP mvp) {	
    	return mvp;

Use format: determines the type of generics when calling methods

public class GenericMethodDemo {
    public static void main(String[] args) {
        // create object
        MyGenericMethod mm = new MyGenericMethod();
        // Tips for demonstration

Interfaces with generics

Definition format:

Modifier interface interface name < variable representing generic > {}

For example,

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

Use format:

1. Determine the type of generics when defining classes

for example

public class MyImp1 implements MyGenericInterface<String> {
    public void add(String e) {
        // Omission...

	public String getE() {
		return null;

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

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

for example

public class MyImp2<E> implements MyGenericInterface<E> {
	public void add(E e) {
       	 // Omission...

	public E getE() {
		return null;

Determine generics:

 * Use
public class GenericInterface {
    public static void main(String[] args) {
        MyImp2<String>  my = new MyImp2<String>();  

Generic wildcard

When a generic class or interface is used, the generic type in the data passed is uncertain and can be represented by the wildcard character <? >. However, once the generic wildcard is used, only the common methods in the Object class can be used, and the element's own methods 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?,? To indicate unknown wildcard.

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

For example, you can understand and use:

public static void main(String[] args) {
    Collection<Intger> list1 = new ArrayList<Integer>();
    Collection<String> list2 = new ArrayList<String>();
public static void getElement(Collection<?> coll){}
//? Delegate can receive any type

tips: the generic type does not have the inheritance relationship Collection list = new ArrayList(); this is wrong.

Advanced use of wildcards -- restricted generics

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

Upper limit of generics:

  • Format: type name <? Extends class > object name
  • Meaning: only this type and its subclasses can be received

Lower bound of generics:

  • Format: type name <? Super class > object name
  • Meaning: only this type and its parent type can be received

For example, now we know the 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(list2);//Report errors
    getElement(list4);//Report errors
    getElement2(list1);//Report errors
    getElement2(list2);//Report errors
// Upper limit of generics: at this time, generics? Must be subclasses of type Number or Number
public static void getElement1(Collection<? extends Number> coll){}
// Lower limit of generics: the generics? At this time must be the parent class of Number type or Number type
public static void getElement2(Collection<? super Number> coll){}

Integrated case

Case introduction

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

Use 54 cards to disorder the order, three players participate in the game, three players touch the cards alternately, each player has 17 cards, and the last three cards are reserved as the base card.

case analysis

  • Prepare cards:

    Cards can be designed as an ArrayList, with each string as a card.
    Each card is composed of two parts: the decor set and the number set. We can nest and iterate to complete the assembly of each card.
    Cards are randomly sorted by the shuffle method of the Collections class.

  • Licensing

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

  • Look at cards

    Print each set directly.

code implementation

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

public class Poker {
    public static void main(String[] args) {
        * 1: Preparation card operation
        //1.1 create deck to store deck in the future 
        ArrayList<String> pokerBox = new ArrayList<String>();
        //1.2 creating a decor collection
        ArrayList<String> colors = new ArrayList<String>();

        //1.3 creating a digital set
        ArrayList<String> numbers = new ArrayList<String>();

        //1.4 add elements to decors and digital collections respectively

        for(int i = 2;i<=10;i++){
        //1.5 operation of creating cards and splicing cards
        // Take out each design and combine it with each number and store it in the card box
        for (String color : colors) {
            //color every Decor 
            //Ergodic number set
            for(String number : numbers){
                String card = color+number;
                //Store in deck
        //1.6 king and Wang
        // System.out.println(pokerBox);
        //Is shuffling the index of the cards in the card box 
        // Collection class tool classes are static methods
        // Shuffler method   
         * static void shuffle(List<?> list) 
         *     Displaces the specified list using the default random source. 
        //2: shuffle
        //3 licensing
        //3.1 create three player sets create a base card 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>();	  

        //Index must be known when traversing the deck   
        for(int i = 0;i<pokerBox.size();i++){
            //Get deck
            String card = pokerBox.get(i);
            //Set aside three cards to store in the bottom card collection
            if(i>=51){//Save to base card collection
            } else {
                //Player 1% 3 = = 0
                }else if(i%3==1){//Player 2
                }else{//Player 3
        //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);  
Published 34 original articles, won praise 8, visited 3429
Private letter follow

Tags: Java JDK SQL

Posted on Tue, 04 Feb 2020 02:58:39 -0800 by MrNonchalant