search
HomeJavajavaTutorialHow to use custom classes to encapsulate arrays in Java to implement data operations

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 数据类型[长度];

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;

The second :

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

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 <h4 id="Add-elements">2.1 Add elements</h4><p>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 <code>9</code>, there are already two elements in the array. , then add the third element as follows: </p><p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168187380584798.png?x-oss-process=image/resize,p_40" class="lazy" alt="How to use custom classes to encapsulate arrays in Java to implement data operations" ></p><pre class="brush:php;toolbar:false">public void add(long value){
    arr[element] = value;
    element++;
}

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 <h4 id="Query-elements-according-to-index">2.3 Query elements according to index</h4><p>To find elements according to index, that is, to obtain the element at the corresponding position, the complexity is O(1). </p><pre class="brush:php;toolbar:false">public long get(int index){
    if(index >= element || index <h4 id="Delete-elements-based-on-index">2.4 Delete elements based on index</h4><p>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: </p><p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168187380647226.png?x-oss-process=image/resize,p_40" class="lazy" alt="How to use custom classes to encapsulate arrays in Java to implement data operations" ></p><p># Theoretically, to delete an element on average, we need to move N/2 times, so its time complexity is also O(N). </p><pre class="brush:php;toolbar:false">public void delete(int index){
    if(index >= element || index <h4 id="Modify-elements">2.5 Modify elements</h4><p>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). </p><pre class="brush:php;toolbar:false">public void change(int index,long newValue){
    if(index >= element || index <h3 id="Ordered-array">3 Ordered array</h3><p>Ordered array is a special type of array. The elements in the ordered array are arranged in a certain order. </p><h4 id="Add-elements">3.1 Add elements</h4><p>When adding elements, add elements to a certain position in order. As follows, add an element <code>33</code> to an array. </p><p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168187380636989.png?x-oss-process=image/resize,p_40" class="lazy" alt="How to use custom classes to encapsulate arrays in Java to implement data operations" ></p><p>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). </p><pre class="brush:php;toolbar:false">public void add(long value){
    int i;
    for (i = 0; i value){
            break;
        }
    }

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

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;
            }
        }
    }
}

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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software