Teach you step by step how to implement List - ArrayList

Table of contents

Foreword:

 linear table

Sequence table

  Implementation of interface

1. Printing sequence table

2. New elements are added at the end of the array by default.

3. Add new elements at pos position 

4. Determine whether a certain element is included

 5. Find the position corresponding to an element

 6. Get the element at pos position

7. Set the element at pos position to value 

8. Delete the first occurrence of the keyword key 

9. Get the sequence table length

10. Clear the sequence list 

Traversal of ArrayList

Problems and thoughts about ArrayList

Foreword:

What is a List?

In the collection framework, List is an interface that inherits from Collection.

From the perspective of data structure, List is a linear list, that is, a limited sequence of n elements of the same type. Operations such as addition, deletion, modification, and variable can be performed on this sequence. 

List provides good methods, as follows:

 

Note: List is an interface and cannot be directly used for instantiation.
If you want to use it, you must instantiate the implementation class of List. In the collection framework, ArrayList and LinkedList are implementedt a> interface. List

In this article we begin The study of ArrayList


 linear table

A linear list is a finite sequence of n data elements with the same characteristics. Linear table is a data structure widely used in practice. Common linear tables: Sequential list, linked list, stack, queue...

A linear table is logically a linear structure, that is, a continuous straight line. However, the physical structure is not necessarily continuous. When linear tables are physically stored, they are usually stored in the form of arrays and linked structures.


Sequence table

A sequence table is a linear structure that uses a storage unit with a continuous physical address to store data elements in sequence. Generally, array storage is used. Complete the addition, deletion, checking and modification of data on the array.

  Implementation of interface

Initialize the array first 

Valid numbers are now useSize 

Simulate all the functions in the interface and basically learn all the functions of the sequence table

The implementation is rewritten in the MyArrayList class

1. Printing sequence table

 Printing the sequence table is relatively simple. You only need to know its userSize and traverse it once.

public void display() {
        for (int i = 0; i < useSize ; i++) {
            System.out.print(elem[i] + "");
        }
        System.out.println();
    }

2. New elements are added at the end of the array by default.

Idea: Find the location of userSize directly and assign the value directly. The effective array userSize is 4

If we need to add 5, assign the value directly to the position with subscript 4

After adding userSize++

Consider the problem carefully. If the array is full, we need to expand it before we can add it. 

All you have to do is determine whether the array is full first. If it is full, expand it first and then add it.

Code:

public void add(int data) {
        //判断
        if(useSize == 5) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        //添加
        elem[useSize] = data;
        useSize++;
    }

 Effect:


3. Add new elements at pos position 

 

Add 11 to 1 subscript 

The elements behind the 1 subscript should be moved to the back, starting from the userSzie-1 subscript and moving to the right. 

And you have to start moving from the rightmost element first

Finally userSize++;

Consider the situation:  

In addition, the pos subscript value cannot be less than 0 or greater than usersize.

Code: 

 public void add(int pos, int data) {
        //先检查是否数组满了吗?
        if(useSize == 5) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        // 判断pos是否合法
        if(pos < 0 || pos > useSize) {
            //抛出异常
            throw new PosException("pos未知不合法" + pos);
        }
        for (int i = useSize - 1; i >= pos ; i--) {
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        useSize++;
    }

 


4. Determine whether a certain element is included

 

Traverse the entire array and then judge

Code:  

   public boolean contains(int toFind) {
        for (int i = 0; i < useSize; i++) {
            if(elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

 5. Find the position corresponding to an element

Code:  

   public int indexOf(int toFind) {
        for (int i = 0; i < useSize; i++) {
            if(elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }


 6. Get the element at pos position

 

The pos here cannot be equal to userSize, otherwise it will cross the boundary. 

Code:  

   public int get(int pos) {
         判断pos是否合法
        if(pos < 0 || pos >= useSize) {
            //抛出异常
            throw new PosException("pos未知不合法" + pos);
        }
        return elem[pos];
    }

7. Set the element at pos position to value 

Code:  

 public void set(int pos, int value) {
        // 判断pos是否合法
        if(pos < 0 || pos > useSize) {
            //抛出异常
            throw new PosException("pos未知不合法" + pos);
        }
        elem[pos] = value;
    }


8. Delete the first occurrence of the keyword key 

 

First determine whether the sequence table is empty. Empty items cannot be deleted.

Delete end userSize-- 

 Code:  

    public void remove(int toRemove) {
        if(useSize == 0){
           throw new EmptyException("顺序表为空");
        }
        //获取toRemove下标
        int index = indexOf(toRemove);
        for (int i = index; i < useSize - 1 ; i++) {
            elem[i] = elem[i+1];
        }
        useSize--;
    }

9. Get the sequence table length

 public int size() {
        return useSize;
    }

10. Clear the sequence list 

 public void clear() {
        useSize = 0;
    }

 The above are basically all the basic operations of the sequence table 


Traversal of ArrayList

1: Print directly

 2: for loop traversal

3. for each traversal

 4. Use iterators


Problems and thoughts about ArrayList

1. The bottom layer of ArrayList uses continuous space. When inserting or deleting elements at any position, the entire subsequent elements at that position need to be moved forward or backward, so the time complexity is O(N)
2. To increase the capacity, you need to apply for new space, copy data, and release old space. There will be a lot of consumption.
3. Capacity expansion generally increases by 2 times, which will inevitably cause a certain amount of waste of space. For example, the current capacity is 100, and when it is full, the capacity is increased to 200. We continue to insert 5 data, and no data will be inserted later, so 95 data spaces are wasted.

When inserting or deleting elements at any position in the ArrayList, you need to move the subsequent elements forward or backward
. The time complexity is O(n), and the efficiency is relatively high. Low, so ArrayList is not suitable for scenarios where there are many insertions and deletions at any position.

Next we will study LinkedList (linked list)

Guess you like

Origin blog.csdn.net/chaodddddd/article/details/134670360