Sequence listArrayList

About the author: zoro-1, currently a sophomore, currently learning Java, data structures, etc.
Author’s homepage: zoro-1’s homepage
Everyone is welcome to like Collect ? Follow!

Sequence table

  • concept
  • Arraylist
    • Construction method
    • Related methods
    • Traversal operation
  • Custom Arraylist
    • interface
    • Implementation class

Concept

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.

Arraylist

Construction method

ArrayList is a class in the Java programming language used to implement dynamically resizable arrays. ArrayList provides multiple construction methods, and you can choose different construction methods according to your needs.

The following are commonly used ArrayList construction methods:

  1. ArrayList(): Create an empty ArrayList with an initial capacity of 10.

  2. ArrayList(int initialCapacity): Create an ArrayList with specified initial capacity.

  3. ArrayList(Collection c): Creates an ArrayList containing the specified elements. This ArrayList contains all elements of the collection according to the iterator order of the specified collection.

Example:

//Create an empty ArrayList
ArrayList<String> list1 = new ArrayList<String>();

//Create an ArrayList with specified initial capacity
ArrayList<Integer> list2 = new ArrayList<Integer>(20);

//Create an ArrayList containing the specified elements
ArrayList<String> list3 = new ArrayList<String>(Arrays.asList("Apple", "Banana", "Orange"));

Note: ArrayList is a generic class and can specify any type as its element type. In the above example, the element types of list1 and list2 are String and Integer, and the element type of list3 is String.

Related methods

ArrayList is a commonly used collection type in Java. It has basic functions such as dynamic addition of elements, random access, and deletion of elements. The specific methods are as follows:

  1. add(E e): Add an element to the end of List.
  2. add(int index, E element): Insert an element at the specified index position.
  3. remove(int index): Remove an element based on index.
  4. remove(Object o): Remove the first element containing the specified element.
  5. clear(): Clear all elements in the List.
  6. get(int index): Returns the element at the specified index position.
  7. set(int index, E element): Replace the element at the specified position with the specified element.
  8. isEmpty(): Returns true if List does not contain any elements.
  9. size(): Returns the number of elements in the List.
  10. contains(Object o): Returns true if List contains the specified element.
  11. indexOf(Object o): Returns the index position of the first matching element, or -1 if not found.
  12. subList(int fromIndex, int toIndex): Returns a sublist in List starting from fromIndex and ending at toIndex – 1 (excluding the toIndex position).

In addition to this, ArrayList also implements the Iterable, Collection, and List interfaces, so you can use the methods defined in these interfaces. For example, you can use the sort(List list) method of the Collections class to sort the elements in an ArrayList. ArrayList is a commonly used collection type in Java. It has basic functions such as dynamic addition of elements, random access, and deletion of elements. The specific methods are as follows:

Traversal operation

  1. Enhanced for loop traversal
ArrayList<String> list = new ArrayList<>();
// add element
for(String element : list){<!-- -->
    System.out.println(element); // Output element
}
  1. Iterator traversal
ArrayList<String> list = new ArrayList<>();
// add element
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){<!-- -->
    String element = iterator.next();
    System.out.println(element); // Output element
}
  1. Lambda expression traversal (Java 8 and later)
ArrayList<String> list = new ArrayList<>();
// add element
list.forEach(element -> System.out.println(element)); // Output elements
```1. Enhance for loop traversal
```java
ArrayList<String> list = new ArrayList<>();
// add element
for(String element : list){<!-- -->
    System.out.println(element); // Output element
}
  1. Iterator traversal
ArrayList<String> list = new ArrayList<>();
// add element
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){<!-- -->
    String element = iterator.next();
    System.out.println(element); // Output element
}
  1. Lambda expression traversal (Java 8 and later)
ArrayList<String> list = new ArrayList<>();
// add element
list.forEach(element -> System.out.println(element)); // Output elements

Customized Arraylist

Interface

public interface IList {<!-- -->
    //New elements are added at the end of the array by default
    public void add(int data);
    //Add element at pos position
    public void add(int pos, int data);
    // Determine whether an element is contained
    public boolean contains(int toFind);
    // Find the position corresponding to an element
    public int indexOf(int toFind);
    // Get the element at pos position
    public int get(int pos);
    // Set the element at pos position to value update
    public void set(int pos, int value);
    //Delete the first occurrence of the keyword key
    public void remove(int toRemove);
    // Get the length of the sequence table
    public int size();
    //Clear the sequence table
    public void clear();
    //Print the sequence table. Note: This method is not the method in the sequence table. It is given for the convenience of viewing the test results.
    public void display();

    boolean isFull();

Implementation class

import java.util.Arrays;

/**
 * @Author 12629
 * @Description:
 */
public class MyArrayList implements IList {<!-- -->


    public int[] elem;
    public int usedSize;//0
    //Default size of sequence table
    public static final int DEFAULT_SIZE = 10;

    public MyArrayList() {<!-- -->
        this.elem = new int[DEFAULT_SIZE];
    }

    public MyArrayList(int capacity) {<!-- -->
        this.elem = new int[capacity];
    }

    /**
     * Traverse the elements in the sequence list
     */
    @Override
    public void display() {<!-- -->
        for (int i = 0; i <this.usedSize; i + + ) {<!-- -->
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }


    @Override
    public void add(int data) {<!-- -->
        checkCapacity();

        this.elem[this.usedSize] = data;
        this.usedSize + + ;
    }

    @Override
    public boolean isFull() {<!-- -->
        /*if(usedSize == elem.length) {
            return true;
        }
        return false;*/

        return usedSize == elem.length;
    }

    @Override
    public void add(int pos, int data) {<!-- -->
        try {<!-- -->
            checkPosOnAdd(pos);
        }catch (PosIllegality e) {<!-- -->
            e.printStackTrace();
            return;
        }
        checkCapacity();
        //1. Start moving backward from the last valid data //2. End when i < pos
        for (int i = usedSize-1; i >= pos; i--) {<!-- -->
            elem[i + 1] = elem[i];
        }
        //3. Store the element at the pos position
        elem[pos] = data;
        //4. usedSize + + ;
        usedSize + + ;
    }
    /**
     * Check the legality of pos
     */
    private void checkPosOnAdd(int pos) throws PosIllegality{<!-- -->
        if(pos < 0 || pos > usedSize) {<!-- -->
            System.out.println("Not legal!");
            throw new PosIllegality("Exception when inserting element subscript: " + pos);
        }
    }

    private void checkCapacity() {<!-- -->
        if(isFull()) {<!-- -->
            //Expansion
            elem = Arrays.copyOf(elem,elem.length*2);
        }
    }

    @Override
    public boolean contains(int toFind) {<!-- -->
        if(isEmpty()) {<!-- -->
            return false;
        }
        for (int i = 0; i < usedSize; i + + ) {<!-- -->
            //If you are looking for a reference data type, be sure to remember the overriding method
            if(elem[i] == toFind) {<!-- -->
                return true;
            }
        }
        return false;
    }

    public boolean isEmpty() {<!-- -->
        return usedSize == 0;
    }

    @Override
    public int indexOf(int toFind) {<!-- -->
        if(isEmpty()) {<!-- -->
            return -1;
        }
        for (int i = 0; i < usedSize; i + + ) {<!-- -->
            //If you are looking for a reference data type, be sure to remember the overriding method
            if(elem[i] == toFind) {<!-- -->
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) throws MyArrayListEmpty{<!-- -->
        checkPosOnGetAndSet(pos);

        if(isEmpty()) {<!-- -->
            throw new MyArrayListEmpty("When getting the specified subscript element" +
                    "The sequence list is empty!");
        }

        return elem[pos];
    }


    private void checkPosOnGetAndSet(int pos) throws PosIllegality{<!-- -->
        if(pos < 0 || pos >= usedSize) {<!-- -->
            System.out.println("Not legal!");
            throw new PosIllegality("Exception in getting the element with the specified subscript: " + pos);
        }
    }

    @Override
    public void set(int pos, int value) {<!-- -->
        checkPosOnGetAndSet(pos);

        elem[pos] = value;
    }

    @Override
    public void remove(int toRemove) {<!-- -->
        int index = indexOf(toRemove);
        if(index == -1) {<!-- -->
            System.out.println("There is no such number!");
            return;
        }
        for(int i = index; i < usedSize-1;i + + ) {<!-- -->
            elem[i] = elem[i + 1];
        }
        usedSize--;

    }

    @Override
    public int size() {<!-- -->
        return this.usedSize;
    }

    @Override
    public void clear() {<!-- -->
        this.usedSize = 0;
    }
}

Today’s sharing ends here. Remember to join us three times. Thank you for your support.