Table of Contents
Array initialization
Two custom classes encapsulate arrays to implement data operations
3.1 Add elements
2.2 Query the element position based on the value
2.3 Query elements according to index
2.4 Delete elements based on index
2.5 Modify elements
3 Ordered array
3.2 Dichotomy method to query index based on elements
Four Summary
Home Java javaTutorial How to use custom classes to encapsulate arrays in Java to implement data operations

How to use custom classes to encapsulate arrays in Java to implement data operations

Apr 19, 2023 am 11:10 AM
java

As a basic data storage structure, arrays are widely used. An array is a data structure that uses continuous memory space to store fixed length and the same data type. The data structure is language-independent. Here, Java is used to perform array-related operations. Array indexes start from 0.

How to use custom classes to encapsulate arrays in Java to implement data operations

Array initialization

There are two ways to create data. One is to declare a fixed-length data first, and then assign a value to the array. The other is to The first is direct assignment.

First type:

数据类型[] 数组名称 = new 数据类型[长度];
Copy after login

The [] mark here declares an array. In addition to being placed after the data type, this [] can also be placed behind the array. After the noun, the effect is the same. If I declare an array of type long with a length of 2, and assign the value:

long[] arr = new long[2];
arr[0] = 1;
arr[1] = 2;
Copy after login

The second :

数据类型[] 数组名称 = {元素1,元素2, ...};
Copy after login

In this way, the array is assigned a value directly when it is initialized. The length of the array is determined by the number of elements.

Two custom classes encapsulate arrays to implement data operations

public class MyArray {

    // 自定义数组    private long[] arr;
    // 有效数据长度    private int element;

    public MyArray(){
        arr = new long[9];
    }

    public MyArray(int maxsize){
        arr = new long[maxsize];
    }
    /**
     * 显示数组元素
     */    public void display(){
        System.out.print("[");
        for (int i = 0; i < element; i++) {
            System.out.print(arr[i]+" ");
        }
        System.out.print("]");
    }
}
Copy after login

2.1 Add elements

Arrays use continuous memory space to store data, so every time they are added, Add an element to the last element of the current array. You can add elements at once, so its complexity is O(1). If you define an array with a length of 9, there are already two elements in the array. , then add the third element as follows:

How to use custom classes to encapsulate arrays in Java to implement data operations

public void add(long value){
    arr[element] = value;
    element++;
}
Copy after login

2.2 Query the element position based on the value

This search method is also called linear search, which is based on the incoming The value loops through the elements to obtain the corresponding position. In theory, it takes N/2 times to query an element on average, so its complexity is O(N).

public int find(long value){
    int i;
    for (i = 0; i < element; i++) {
        if(value == arr[i]){
            break;
        }
    }
    if(i == element){
        return -1;
    }else {
        return i;
    }
}
Copy after login

2.3 Query elements according to index

To find elements according to index, that is, to obtain the element at the corresponding position, the complexity is O(1).

public long get(int index){
    if(index >= element || index < 0){
        throw new ArrayIndexOutOfBoundsException();
    }else {
        return arr[index];
    }
}
Copy after login

2.4 Delete elements based on index

After deleting the element corresponding to the index, we need to move all elements after the index forward one position. If I want to delete the element with index 2, as follows:

How to use custom classes to encapsulate arrays in Java to implement data operations

# Theoretically, to delete an element on average, we need to move N/2 times, so its time complexity is also O(N).

public void delete(int index){
    if(index >= element || index < 0){
        throw new ArrayIndexOutOfBoundsException();
    }else {
        for (int i = index; i < element; i++) {
            arr[index] = arr[index+1];
        }
        element --;
    }
}
Copy after login

2.5 Modify elements

Modify the element at a certain position and modify the corresponding element directly according to the index once, so its time complexity is O(1).

public void change(int index,long newValue){
    if(index >= element || index < 0){
        throw new ArrayIndexOutOfBoundsException();
    }else {
        arr[index] = newValue;
    }
}
Copy after login

3 Ordered array

Ordered array is a special type of array. The elements in the ordered array are arranged in a certain order.

3.1 Add elements

When adding elements, add elements to a certain position in order. As follows, add an element 33 to an array.

How to use custom classes to encapsulate arrays in Java to implement data operations

First, move the element with index 3 to index 4, then move the element with index 2 to index 3, and finally add 33 to index 2. Theoretically, inserting an element requires moving N/2 elements, so its time complexity is O(N).

public void add(long value){
    int i;
    for (i = 0; i < element; i++) {
        if(arr[i]>value){
            break;
        }
    }

    for (int j = element; j > i; j--){
        arr[j] = arr[j-1];
    }
    arr[i] = value;
    element++;
}
Copy after login

3.2 Dichotomy method to query index based on elements

In an unordered array, use the linear method to find related elements. The linear method is to search one by one according to the index. Sorted arrays can use the dichotomy method to find elements. Dichotomy means dividing an array into two from the middle, determining which array the element is in, and then repeating this operation.

Suppose there is an array with 8 elements. The content of the array is an ordered sequence of 0-7. To find the element 5, it is divided into 0-3 and 4-7 for the first time. Two arrays, then divide 4-7 into two arrays 4-5 and 6-7, and finally divide 4-5 into 4 and 5 to query the specific elements. In this way, after dividing 3 times, you can query the length of The complexity of specific elements in an array of 8 is O(logN) (the base of logN in computers generally refers to 2, which means that the power of 2 is equal to n).

public int search(long value){
    // 中间值    int middle = 0;
    // 最小值    int low = 0;
    // 最大值    int pow = element;
    while (true){
        middle = (low + pow) / 2;
        if(arr[middle] == value){
            return middle;
        }else if (low > pow){
            return -1;
        }else{
            if(arr[middle] > value){
                pow = middle - 1;
            }else{
                low = middle + 1;
            }
        }
    }
}
Copy after login

Four Summary

The lower the complexity means the algorithm is better, so O(1) > O(logN) > O(N) > O(N^2) .

Algorithm Complexity
Linear search O(N)
Binary search O(logN)
Unordered array insertion O(1)
Ordered array insertion O(N)
Unordered array deletion O(N)
Ordered array deletion O(N)
  1. Unordered array insertion is fast, search and deletion are slow

  2. Ordered array search is fast, insertion and deletion are slow

The above is the detailed content of How to use custom classes to encapsulate arrays in Java to implement data operations. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
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

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

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles