Detailed Explanation of Java Collections (1)

Table of contents

1. Collection overview:

2. Common methods of collection

3. Iterator

4. Enhanced for loop


1. Collection overview:

 1.1 Collection Introduction:

  • A collection is a container provided by Java that can store multiple data.
  • All Java collection classes are located under the java.util package, providing a unified framework for representing and manipulating object collections, including a large number of collection interfaces, implementation classes of these interfaces, and some implementation algorithms

  1.2 The difference between collections and arrays:

  • Length: The length of the collection can be changed, and the length of the array is fixed
  • Store data: All collections store are reference data types, and arrays can store both reference data types and basic data types. Arrays can only store one data type

Note: Collections can also store basic data types, as long as the corresponding wrapper class is stored. Such as int-->integer

 list.add(20); //相当于自动装箱,Integer i=20;
       

  1.3 Inheritance collection system of commonly used collection classes:

Java collections are divided into two root interfaces, collction and Map. These two interfaces contain subinterfaces (interfaces can be inherited between interfaces) and implementation subclasses.

The details are as follows:

Yellow is the interface, and blue is the implementation class;

  • The Iterator interface is an output interface, which is used to traverse the elements in the output collection set (iterative output). The literator object is an iterator . When the implementation class implements collection, it must also implement lierator.
  • collection has three sub-interfaces, namely java.util.List, java.utli.Set and java.util.queue. List stores non-repeating, ordered elements, set stores repeated elements, and Queue is a queue implementation provided by Java
  • ListThe main implementation class of the interface is java.util.ArrayListand java.util.LinkedList, and Setthe main implementation class of the interface is java.util.HashSetand java.util.LinkedHashSet.

Note: The interface just provides a specification, telling us what we must do. When we want to operate on the elements in the collection, we need to implement subclasses, instantiate objects, call methods, and implement operations.

Divide the collection into interfaces, implement subclasses, and the algorithm more clearly reflects its inheritance system

As shown below:

2. Common methods of collection: 

Collection is the parent interface of all single-column collections. For its subinterfaces and implementation subclasses, the collction method is also common.

2.1 Common methods and functions of collection:


1.void clear() clears all collection elements
2.boolean contains(Object o) judges whether the specified collection contains object o
3.boolean contains(Object 0) judges whether the current collection contains the given object.
4.boolean isEmpty() Determines whether the size of the element in the specified collection is 0
5.boolean remove(Object o) Deletes the element object o in the collection. If the collection has multiple o elements, only the first element will be deleted
7.int size() The number of elements in the collection
8.T[] toArray(T[] a) Convert the collection to an array of type T

9.boolean add(E e) Adds element e to the collection, and returns true if the specified collection element has changed

10 . Object[] toArray(): Store the elements in the collection into an array.

Code demo:

public class Oopjihe {
    public static void main(String[] args) {
        //创建一个集合对象
        ArrayList list = new ArrayList();
        //判断集合长度
        int startsize=list.size();
        list.add("hello");
        list.add("add");
        list.add("20");
        list.add(20);
        //相当于自动装箱,
        Integer i=20;
        //判断长度
        int endsize=list.size();
        //移除某个元素
        list.remove("hello");
        //判断是否有这个元素
        boolean b1=list.contains("hello");
        System.out.println(b1);//flase
        //判断集合是否为空
        boolean b2=list.isEmpty();
        System.out.println(b2);//flase

        //清除所有元素
        list.clear();

        boolean b3=list.isEmpty();
        System.out.println(b3);//true

  2.2 Method extension:

  get(int index) ;

  Function: Get the corresponding subscript element in the collection.

TocharArray() or TostringArray():

Function: Convert the elements in the collection to char array or string array

case analysis:

Define a List collection of String type, and count the number of occurrences of each character (note, not a string) in the collection. 
For example: there are two elements "abc" and "bcd" in the set, the final output of the program is: "a = 1, b = 2, c = 2, d = 1"
import java.util.ArrayList;
public class Excel3 {
    public static void main(String[] args) {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("adc");
        strings.add("bcc");
        int count[]=new int[3];//计数器

        //把集合中的元素转为char数组
        for(int i=0;i<strings.size();i++){
            char[] str1=strings.get(i).toCharArray();
            //把统计char数组中元素
            for(char ch:str1){
                System.out.println(ch+" ");
                if('a'==ch){
                    count[0]++;
                }else if('b'==ch){
                    count[1]++;
                }else if('c'==ch){
                    count[2]++;
                }
            }
            System.out.println("a的元素个数="+count[0]);
            System.out.println("b的元素个数="+count[1]);
            System.out.println("c的元素个数="+count[2]);

        }

3. Iterator 

  3.1 Introduction to iterators:

  • Iteration is a way of traversing the collection elements. Before taking the element, first judge whether there is an element in the collection, and if so, take the element out. Continue to judge, if there is, continue to get elements until all elements in the collection are taken out. The technical term for this way of taking out is iteration .

  • An iterator is actually an instantiated object of an implementation class. In a ArrayListcollection Iteratormethod, Itran iterator is obtained by returning an object. Itris ArrayListan inner class that implements Iteratorthe interface
  • In program development, it is often necessary to traverse all elements in a collection. In response to this demand, JDK provides an interface specifically java.util.Iterator, iterator is called iterator

  3.2 The use of iterators:

Step 1: Get an iterator

Iterator iterator1= collection.iterator();

Step 2: Use the three methods of the iterator to operate on the elements.

There are three methods in iterator:

boolean hasNext():   Determine whether there is a next element
E next():    Return the next element
void remove():    Delete the next element

Example of use:

//定义一个迭代器。输出集合中的元素
            Iterator iterator = arrayList.iterator();//获取迭代器
            while (iterator.hasNext()){//判断下一个是否有元素
                Object s=iterator.next();//下一个元素
                System.out.println(s);
            }

important point:

  1. When obtaining collection elements, if there are no more elements in the collection and the next method of the iterator continues to be used, a java.util.NoSuchElementException will be thrown without a collection element exception.

  2. When acquiring collection elements, if you add or remove elements in the collection, you will not be able to continue iterating, and a ConcurrentModificationException will be thrown.

  3. If you must delete an element, use the iterator's own remove method.

      Iterator iterator =list.iterator();
    
            while(iterator.hasNext()){
                System.out.println("长度为"+list.size());
    //            list.add("集合2");//在集合移除或者添加过程中,迭代获取元素会报错。
    //            list.remove("20");
               String name=iterator.next().toString();
               if("20".equals(name)){
                   iterator.remove();
               }else{
                   System.out.println(name);
               }

      3.3. Iterator implementation principle:

When the Iterator iterator object traverses the collection, it internally uses pointers to track the elements in the collection.

Before calling the next method of Iterator, the index of the iterator is before the first element and does not point to any element. Before calling the next method, the hasnext() method will be called to determine the next element, and if it is true, the next method will be called.

When the next method of the iterator is called for the first time, the index of the iterator will move backward one bit, pointing to the first element and returning the element. Before calling the next method again, the hasnext() method will be called again to judge An element that calls the next method if true. The index of the iterator will point to the second element and return that element, and so on, until the hasNext method returns false, indicating that the end of the collection has been reached, terminating the traversal of the elements.

4. Enhanced for loop:

 The enhanced for loop (also known as the for each loop) is an advanced for loop that came out after JDK1.5 , and is specially used to traverse arrays and collections. Its internal principle is actually an Iterator iterator, so during the traversal process, elements in the collection cannot be added or deleted.

for(变量类型 变量 :数组/集合){
    处理遍历的数据,数据就保存在这个变量上面
}

Note: Because foreach uses an iterator at the bottom, do not add or delete collection elements when traversing the collection.  

the case

The array is known to store a batch of QQ numbers, the longest QQ number is 11 digits, and the shortest is 5 digits 
String[] strs = {"12345","67891","12347809933","98765432102","67891","12347809933" }. 
Store all the qq numbers in the array in the LinkedList, delete the duplicate elements in the list, and print out all the elements in the list with iterators and enhanced for loops

import java.util.ArrayList;
import java.util.Iterator;

public class Excel2 {
    public static void main(String[] args) {
        String[] strs = {"12345","67891","12347809933","98765432102","67891","12347809933"};
        //定义一个集合
        ArrayList arrayList = new ArrayList();
        //将数组中的元素放到集合中
        for(int i=0;i<strs.length;i++){
            arrayList.add(strs[i]);
        }
        //将list中的重复元素删除
       for(int i=0;i<arrayList.size();i++){
           Object a1=arrayList.get(i);//拿到集合中的元素
           for(int j=i+1;j<arrayList.size();j++){
               Object j1 = arrayList.get(j);

//               if(arrayList.contains(a1)){
           if(j1==a1){
               arrayList.remove(a1);
               i=i-1;
           }

               }
//           }
       }
       //增强for循环:
        for(Object a:arrayList){
            System.out.println(a);
        }

    }
}

Guess you like

Origin blog.csdn.net/qq_50692350/article/details/126166502
Recommended