Table of Contents
1. Linear table
Definition
Features
2. Sequence table
Implementation
Print array
Add new elements
Determine whether a certain element is contained
Finding elements
Get the element at pos position
Change the value of pos position
Delete operation
Get the sequence table length
Clear the sequence table
3. ArrayList
Introduction:
Using
Some common methods
Home Java javaTutorial How to define and implement ArrayList and sequence list in Java

How to define and implement ArrayList and sequence list in Java

May 18, 2023 pm 02:04 PM
java arraylist

    1. Linear table

    Definition

    Linear table is the most basic, simplest, and most commonly used data structure. A finite sequence, which contains n data elements with the same characteristics, is called a linear list and is a type of data structure.

    Common linear lists: sequential lists, linked lists, stacks, queues...

    Linear lists are logically linear structures, that is to say, they are a continuous straight line. The physical storage form of linear tables is usually an array or linked list structure, but it is not necessarily continuous.

    Features

    • #There must be only one "first element" in the set.

    • There must be only one "last element" in the set.

    • Except for the last element, all elements have a unique successor (successor).

    • Except for the first element, all elements have a unique predecessor (antecedent).

    2. Sequence table

    Definition

    The linear structure usually stored in the form of an array is called a sequence table, which stores data elements in sequence in a physical in memory cells with consecutive addresses. Complete the addition, deletion, checking and modification of data on the array.

    Implementation

    First we need to create an array to store data.

    How to define and implement ArrayList and sequence list in Java

    Note: Because I created the integer array first for convenience, in order to better adapt to various types, you can create a generic array, which I don’t have here. wrote.

    How to define and implement ArrayList and sequence list in Java

    The next step is to perform various operations on the sequence table. For example: basic CURD, print sequence table, get sequence table length, clear sequence table, etc.

    Because it is an array, just traverse the array and print it directly

    How to define and implement ArrayList and sequence list in Java

    Add new elements

    When adding elements, it is necessary to consider whether the array is full, so we need to make a judgment. If the array space is full, it needs to be expanded. In addition, we also need to determine whether this pos position is legal.

    Method to determine whether the space is full

    How to define and implement ArrayList and sequence list in Java

    Here we simplify the code as:

    How to define and implement ArrayList and sequence list in Java

    If you want In the case of expansion, after the expansion is completed, because the sequence list is a continuous structure, if a new element is added at the pos position, the elements after the pos position will be moved back in sequence. Only in this way can new elements be added.

    How to define and implement ArrayList and sequence list in Java

    Note: After expansion, we need to change the size of CAPACITY and usedSize.

    Determine whether a certain element is contained

    Here we need to consider whether the array is empty at this time.

    How to define and implement ArrayList and sequence list in Java

    After that, it is still a direct traversal of the array.

    How to define and implement ArrayList and sequence list in Java

    Finding elements

    A null operation is also required here.

    How to define and implement ArrayList and sequence list in Java

    Get the element at pos position

    There may be situations where the array is empty and pos is illegal, so judgment is required.

    I am manually throwing exceptions here, and I have not written anything else.

    How to define and implement ArrayList and sequence list in Java

    Change the value of pos position

    How to define and implement ArrayList and sequence list in Java

    Delete operation

    Delete an element at a certain position , you can directly let the elements behind it cover it to achieve deletion.

    How to define and implement ArrayList and sequence list in Java

    Get the sequence table length

    How to define and implement ArrayList and sequence list in Java

    Clear the sequence table

    How to define and implement ArrayList and sequence list in Java

    The following operations are relatively simple and will not be described in detail.

    3. ArrayList

    Introduction:

    In the collection framework, ArrayList is an ordinary class that implements the List interface. The specific framework diagram is as follows:

    How to define and implement ArrayList and sequence list in Java

    [Explanation]

    1. ArrayList implements the RandomAccess interface, indicating that ArrayList supports random access.

    2. ArrayList implements the Cloneable interface, indicating that ArrayList can be cloned.

    3. ArrayList implements the Serializable interface, indicating that ArrayList supports serialization.

    4. Unlike Vector, ArrayList is not thread-safe and can be used in a single thread. In multi-threads, you can choose Vector or CopyOnWriteArrayList.

    5. The bottom layer of ArrayList is a continuous space and can be dynamically expanded. It is a dynamic type sequence list.

    Using

     public static void main(String[] args) {
            // ArrayList创建,推荐写法
            // 构造一个空的列表
            List<Integer> list1 = new ArrayList<>();
     
            // 构造一个具有10个容量的列表
            List<Integer> list2 = new ArrayList<>(10);
            list2.add(1);
            list2.add(2);
            list2.add(3);
     
            // list2.add("hello"); // 编译失败,List<Integer>已经限定了,list2中只能存储整形元素
            // list3构造好之后,与list中的元素一致
            ArrayList<Integer> list3 = new ArrayList<>(list2);
     
            // 避免省略类型,否则:任意类型的元素都可以存放,使用时将是一场灾难
            List list4 = new ArrayList();
            list4.add("111");
            list4.add(100);
        }
    Copy after login

    Some common methods

    MethodExplanation
    boolean add(E e)End insert e
    void add(int index, E element)will e is inserted into the index position
    boolean addAll(Collection c)Insert the end of the elements in collection c into the collection
    E remove(int index)Remove the index position element and return
    boolean remove(Object o) Delete the first o
    E get(int index)Get the subscript index position element
    E set(int index, E element)Set the subscript index position element to element
    void clear()Clear the sequence table
    boolean contains(Object o)Judge whether o is in the linear table
    int indexOf(Object o)Return the subscript of the first o
    int lastIndexOf(Object o)Return the subscript of the last o
    List< E > subList(int fromIndex, int toIndex)Interception of part of the list
    ## ArrayList traversal

    Loop traversal

    How to define and implement ArrayList and sequence list in Java

    foreach traversal

    How to define and implement ArrayList and sequence list in Java##Iterator

            System.out.println("======迭代器1=========");
     
            ElementObservableListDecorator<Object> list;
            Iterator<String> it =  list.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
            System.out.println("======迭代器2=========");
            ListIterator<String> it2 =  list.listIterator();
            while (it2.hasNext()) {
                System.out.println(it2.next());
            }
    Copy after login

    Sequence table and The difference between arrays:

    As mentioned above, the bottom layer of the sequence table can be understood as an array, but it is more advanced than an array.

    The sequence table can expand by itself;

    The sequence table strictly distinguishes between the array capacity and the number of elements.

    So an array is actually an incomplete sequence list.

    Notes in the sequence table:

      We need to distinguish between two concepts in the sequence table: capacity and the number of elements (size).
    • Capacity can be understood as the size (length) of the array, and the number of elements is the number of valid elements recorded in size.
    • In a sequence table, data storage needs to be continuous, and there cannot be "gaps" between elements. When operations such as insertion and deletion are performed, after the operation is completed, Ensure the continuity of the sequence list.

    The above is the detailed content of How to define and implement ArrayList and sequence list in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

    Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

    Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

    Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

    PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

    PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

    PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

    PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

    Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

    See all articles