Advanced JAVA - Commonly used APIs of the Collection class and collection traversal methods

Table of contents

        1.0 Collection class description

        1.1 Instance methods in Collection class

        ​ ​ 2.0 Collection traversal method of collection (key points)

        2.1 Use iterator (Iterator) to traverse

        2.2 Use enhanced for loop to traverse

        ​ ​ 2.3 Use Java 8’s Stream API to traverse (use Lambda expressions to traverse)


        ​ ​ 1.0 Collection class description

        The Collection class is the root interface in the Java single-column collection framework and is the parent interface of all single-column collection classes. CollectionThe interface has multiple implementation classes, the commonly used ones areArrayList: based on arrays The implemented dynamic array supports random access and fast insertion and deletion of elements.

        1.1 Instance methods in Collection class

The code is as follows (introduced as an example):

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

public class CollectionAPI {

    public static void main(String[] args) {
        //因为 Collection 是接口,故不能直接创建对象,
        // 那么需要利用它实现类 ArrayList 类,且支持泛型类
        Collection<String> collection = new ArrayList<>();

        // 1. Collection 中 add() 的实例方法,添加元素
        collection.add("二哈");
        collection.add("金毛");
        collection.add("拉布拉多");
        collection.add("中华田园犬");
        collection.add("二哈");
        System.out.println(collection);
        //输出结果为:[二哈, 金毛, 拉布拉多, 中华田园犬, 二哈]

        // 2. Collection 中 size() 的实例方法,获取集合的大小
        System.out.println(collection.size());
        //输出结果为:5
        
        // 3. Collection 中 contains() 的实例方法,
        // 判断是否包含某个元素,是则返回true ,不是则返回false
        System.out.println(collection.contains("二哈"));
        //输出结果为:true

        // 4. Collection 中 remove() 的实例方法
        // 删除某个元素,如果是该元素是重复的时候,删除的是第一个该元素
        collection.remove("二哈");
        System.out.println(collection);
        //输出的结果为:[金毛, 拉布拉多, 中华田园犬, 二哈]

        // 5. Collection 中 clear() 的实例方法,清空集合中的元素
        collection.clear();
        System.out.println(collection);
        //查看集合中的元素,输出结果为: []

        // 6. Collection 中 isEmpty() 的实例方法,
        // 判断集合元素是否为空,是空则放回true,不是空则返回false
        System.out.println(collection.isEmpty());
        //输出结果为:true

        // 7. Collection 中 toArray() 的实例方法,把集合转化为数组
        //先添加一些元素
        collection.add("二哈");
        collection.add("二哈");
        //调用 toArray() 的实例方式,类型是 String 类型,
        //虽然集合支持泛型,但是在运行的时候会被擦除,所以为了兼容,
        //建议用所以用 Object[] 类型的数组来接收
        Object[] str = collection.toArray();
        System.out.println(Arrays.toString(str));
        //输出的结果为:[二哈, 二哈]
        
    }
}

The running results are as follows:

        ​ ​ 2.0 Collection traversal method of collection (key points)

        Let me ask two questions first. Why can’t we use ordinary for loop for collection traversal? Is there any way to traverse a collection?

        Answer the first question: You cannot use the ordinary for loop for collection traversal because the number of elements in the collection class changes dynamically. , while the ordinary for loop traverses based on a fixed number of elements. When the number of elements in the collection class changes, the ordinary for loop cannot correctly traverse all elements, and errors such as out-of-bounds errors may occur.

        Answer the second question: Collection There are three main ways to traverse a collection: using iterator (Iterator)To traverse, useEnhanced for loopTo traverse, use Lambda expression to traverse (you can use Stream 's forEach() method traversal)

        2.1 Use iterator (Iterator) to traverse

        First obtain an iterator object by calling the iterator() method of the collection, and then use while Loops and iterators hasNext() and next() a> method to traverse.

code show as below:

  

import java.util.*;
public class CollectionAPI {

    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();
        c.add("二哈");
        c.add("金毛");
        c.add("拉布拉多");
        c.add("中华田园犬");
        //使用迭代器( Iterator )进行遍历:
        //首先需要通过 iterator() 方法获取一个迭代器对象,
        Iterator iterator = c.iterator();
        //然后使用 while 循环和迭代器的 hasNext() 和 next() 方法进行遍历.
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

The running results are as follows:

        Detailed explanationhasNext() and next() methods , hasNext() Determine whether the element in the currently pointed set is empty, if it is empty, return false  does two actions. The first action is to obtain the current collection element, and the second action is to point to the next collection element. element. To make it coherent, we first get the element currently pointed to, and then point to the element in the next set. next(). true , otherwise it returns

        ​ ​ ​ Supplement: Iterators cannot be used for arrays because iterators are a data access method in the collection framework, and arrays do not belong to the collection framework. It is a basic data structure in the Java language, so iterators cannot be used.

        2.2 Useenhanced for loop to traverse

         Enhanced for loop can directly traverse the elements in the collection without using an iterator. But the essence is still the use of iterators. Enhanced for loop is a simplified way of writing iterators.

        As a matter of common sense: when using enhanced for loop to traverse a collection, the compiler will automatically generate an iterator for us. And use the iterator's hasNext() and next() methods to Iterate over the elements in the collection. Therefore, although we do not need to explicitly call the iterator method when using the enhanced for loop, we are actually using iteration indirectly. device. (Enhance the for loopThe purpose is to simplify the code)

        Another thing to note is that for arrays, we cannot directly use iterators to traverse. Iterators are used to traverse collection classes (such as List, Set, etc. ) data structure tool, and array is not a collection class, it is a basic data structure. However, for arrays, we can directly use the enhanced for loop.

code show as below:

import java.util.*;
public class CollectionAPI {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();
        c.add("二哈");
        c.add("金毛");
        c.add("拉布拉多");
        c.add("中华田园犬");

        for (String s : c) {
            System.out.println(s);
        }
    }
}

The running results are as follows:

        ​ ​ 2.3 Use Java 8’s Stream API to traverse (use Lambda expressions to traverse)

        Java 8 introduced the Stream API, you can use Stream's forEach() method to traverse the elements in the collection.

       forEach() The parameters in the instance method provided in the collection are anonymous inner classes Consumer< >   is a functional interface, and you need to override the accept() method inside the interface.

        EssenceforEach() The method isEnhanced for loop , you can take a look at the original code:

code show as below:

public class CollectionAPI {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();
        c.add("二哈");
        c.add("金毛");
        c.add("拉布拉多");
        c.add("中华田园犬");

/*        c.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        });*/

        //之所以可以称为 Lambda 表达式遍历,
        // 是因为可以用 Lambda 表达式来遍历
        c.forEach( s -> System.out.println(s) );

        System.out.println("----------------------");
        //还可以继续简化
        c.forEach( System.out::println);
    }
}

The running results are as follows:

  

 If you are not familiar with the use of anonymous inner classes or Lambda expressions, you can click on the following link to learn more: < /span>

Advanced JAVA - Lambda expressions and omission rules for Lambda expressions - CSDN Blog



Guess you like

Origin blog.csdn.net/Tingfeng__/article/details/133929877