Collection, generic

primary coverage

Learning objectives

Chapter 1 collection

1.1 collection overview

Since both sets and arrays are containers, what is the difference between them?

1.2 collection framework

Java provides APIs to meet various requirements. Before using these APIs, you should first understand their inheritance and interface operation architecture, so as to understand when to adopt which class 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 collections and Java util. Collection and double column collection Java util. Map, today we mainly study the collection collection, and later we will study the map collection.

From the above description, it can be seen that JDK provides rich collection class libraries. In order to facilitate systematic learning, next, a diagram is used to describe the inheritance system of the whole collection class.

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 study the collection classes listed in the figure one by one.

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 for 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:

Method demonstration:

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

public class Demo1Collection {
    public static void main(String[] args) {
		// 创建集合对象 
    	// 使用多态形式
    	Collection<String> coll = new ArrayList<String>();
    	// 使用方法
    	// 添加功能  boolean  add(String s)
    	coll.add("小李广");
    	coll.add("扫地僧");
    	coll.add("石破天");
    	System.out.println(coll);	//[小李广,扫地僧,石破天]

    	// boolean contains(E e) 判断o是否在集合中存在
    	System.out.println("判断  扫地僧 是否在集合中"+coll.contains("扫地僧"));	//判断  扫地僧 是否在集合中true

    	//boolean remove(E e) 删除在集合中的o元素
    	System.out.println("删除石破天:"+coll.remove("石破天"));	//删除石破天:true
    	System.out.println("操作之后集合中元素:"+coll);
    	
    	// size() 集合中有几个元素
		System.out.println("集合中有"+coll.size()+"个元素");

		// Object[] toArray()转换成一个Object数组
    	Object[] objects = coll.toArray();
    	// 遍历数组
    	for (int i = 0; i < objects.length; i++) {
			System.out.println(objects[i]);
		}

		// void  clear() 清空集合
		coll.clear();
		System.out.println("集合中内容为:"+coll);
		// boolean  isEmpty()  判断是否为空
		System.out.println(coll.isEmpty());  	
	}
}

Chapter 2 iterator iterator

2.1 iterator interface

In program development, it is often necessary to traverse all elements in the collection. To meet this requirement, 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 collection iterator to complete the iterative operation. The following describes the method of obtaining the iterator:

Here is the concept of iteration:

The common methods of iterator interface are as follows:

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) {
        // 使用多态方式 创建对象
        Collection<String> coll = new ArrayList<String>();

        // 添加元素到集合
        coll.add("串串星人");
        coll.add("吐槽星人");
        coll.add("汪星人");
        //遍历
        //使用迭代器 遍历   每个集合对象都有自己的迭代器
        Iterator<String> it = coll.iterator();
        //  泛型指的是 迭代出 元素的数据类型
        while(it.hasNext()){ //判断是否有迭代元素
            String s = it.next();//获取迭代出的元素
            System.out.println(s);
        }
  	}
}

2.2 implementation principle of iterator

We have completed the whole process of iterator traversing the collection in the previous case. When traversing the collection, first obtain the iterator object by calling the iterator () method of the T collection, and then use the hashnext () method to judge whether there is the next element in the collection. If so, call the next () method to take out the element. Otherwise, it indicates that the end of the collection has been reached, and stop traversing the element.

When the iterator iterator object traverses the set, it internally uses a pointer to track the elements in the set. In order to better understand the working principle of the iterator, next, a legend is used to demonstrate the iterative process of the iterator object:

Before calling the next method of the iterator, the iterator's index 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 iterator's index will move back one bit, point to the first element and return the element. When calling the next method again, the iterator's index will point to the second element and return the element, And so on, until the hasnext method returns false, indicating 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 you can't add or delete elements in the collection during traversal.

Format:

for(元素的数据类型  变量 : Collection集合or数组){ 
  	//写操作代码
}

It is used to traverse collections and arrays. Generally, only elements are traversed. Do not add or delete collection elements during traversal.

Exercise 1: traversing an array

public class NBForDemo1 {
    public static void main(String[] args) {
		int[] arr = {3,5,6,87};
       	//使用增强for遍历数组
		for(int a : arr){//a代表数组中的每个元素
			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("小河神");
    	coll.add("老河神");
    	coll.add("神婆");
    	//使用增强for遍历
    	for(String s :coll){//接收变量s代表 代表被遍历到的集合元素
    		System.out.println(s);
    	}
	}
}

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);//由于集合没有做任何限定,任何类型都可以给其中存放
		Iterator it = coll.iterator();
		while(it.hasNext()){
			//需要打印每个字符串的长度,就要把迭代出来的对象转成String类型
			String str = (String) it.next();
			System.out.println(str.length());
		}
	}
}

A problem occurred while the program was running lang.ClassCastException。 Why do type conversion exceptions occur? Let's analyze: because any type of element in the collection can be stored. Causes a runtime ClassCastException to be thrown when fetching. How to solve this problem? Although a collection can store various objects, in fact, a collection usually stores only 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 at compile time.

3.2 benefits of using generics

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

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);//当集合明确类型后,存放类型不一致就会编译报错
        // 集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = it.next();
            //当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
            System.out.println(str.length());
        }
	}
}

3.3 definition and use of generics

We will make a lot of use of generics in the collection. Here we can learn about 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 that contain generics

Define format:

修饰符 class 类名<代表泛型的变量> {  }

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 generics are determined.

Determine generics when creating objects

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

At this time, the value of variable E is of 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> {
	//没有MVP类型,在这里代表 未知的一种数据类型 未来传递什么就是什么类型
	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) {		 
         // 创建一个泛型为String的类
         MyGenericClass<String> my = new MyGenericClass<String>();    	
         // 调用setMVP
         my.setMVP("大胡子登登");
         // 调用getMVP
         String mvp = my.getMVP();
         System.out.println(mvp);
         //创建一个泛型为Integer的类
         MyGenericClass<Integer> my2 = new MyGenericClass<Integer>(); 
         my2.setMVP(123);   	  
         Integer mvp2 = my2.getMVP();
    }
}

Methods with generics

Define format:

修饰符 <代表泛型的变量> 返回值类型 方法名(参数){  }

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 the generic when a method is called

public class GenericMethodDemo {
    public static void main(String[] args) {
        // 创建对象
        MyGenericMethod mm = new MyGenericMethod();
        // 演示看方法提示
        mm.show("aaa");
        mm.show(123);
        mm.show(12.45);
    }
}

Interface with generics

Define format:

修饰符 interface接口名<代表泛型的变量> {  }

For example,

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

Use format:

1. Determine the type of generic when defining a class

for example

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

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

At this point, the value of generic e is of type string.

2. The type of a generic is always uncertain until the type of the generic is determined when the object is created

for example

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

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

Determine generics:

/*
 * 使用
 */
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){}
//?代表可以接收任意类型
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>