Home Java javaTutorial Data Structures: Arrays

Data Structures: Arrays

Aug 11, 2024 pm 08:35 PM

Data Structures: Arrays

Static Array

Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of same data type stored at contiguous memory locations.

Initialization

1

2

3

4

5

6

7

8

9

10

11

12

13

public class Array<T> {

    private T[] self;

    private int size;

    @SuppressWarnings("unchecked")

    public Array(int size) {

        if (size <= 0) {

            throw new IllegalArgumentException("Invalid array size (must be positive): " + size);

        } else {

            this.size = size;

            this.self = (T[]) new Object[size];

        }

    }

}

Copy after login

In Core Array Class, we are going to store size of array and a general skeleton for array initialization. In constructor, we are asking for size of array and making an object and type casting it in our desired array.

Set Method

1

2

3

4

5

6

7

public void set(T item, int index) {

        if (index >= this.size || index < 0) {

            throw new IndexOutOfBoundsException("Index Out of bounds: " + index);

        } else {

            this.self[index] = item;

        }

    }

Copy after login

This method is asking for an item to be stored in array and index on which item should be stored.

Get Method

1

2

3

4

5

6

7

public T get(int index) {

        if (index >= this.size || index < 0) {

            throw new IndexOutOfBoundsException("Index Out of bounds");

        } else {

            return self[index];

        }

    }

Copy after login

Get Method asks for an index and retrives item from that index.

Print Method

1

2

3

4

5

public void print() {

        for (int i = 0; i < size; i++) {

            System.out.println(this.self[i]+" ");

        }

    }

Copy after login

Print Method is just printing all members of an array in a single line with a space seperating each item between them.

Sorted Array

Arrays but having a functionality to sort elements itself.

Initialization

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public class SortedArray<T extends Comparable<T>> {

    private T[] array;

    private int size;

    private final int maxSize;

    @SuppressWarnings("unchecked")

    public SortedArray(int maxSize) {

        if (maxSize <= 0) {

            throw new IllegalArgumentException("Invalid array max size (must be positive): " + maxSize);

        }

        this.array = (T[]) new Comparable[maxSize];

        this.size = 0;

        this.maxSize = maxSize;

    }

}

Copy after login

In Sorted Array Class, we are going to store size of array and ask for Max size of array as well and a general skeleton for array initialization. In constructor, we are asking for Max Size of array and making an object and type casting it in our desired array.

Getters

1

2

3

4

5

6

7

8

9

10

11

12

13

public int length() {

        return this.size;

    }

 public int maxLength() {

        return this.maxSize;

    }

 public T get(int index) {

        if (index < 0 || index >= this.size) {

            throw new IndexOutOfBoundsException("Index out of

 bounds: " + index);

        }

        return this.array[index];

    }

Copy after login

Insertion Method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

private int findInsertionPosition(T item) {

        int left = 0;

        int right = size - 1;

        while (left <= right) {

            int mid = (left + right) / 2;

            int cmp = item.compareTo(this.array[mid]);

            if (cmp < 0) {

                right = mid - 1;

            } else {

                left = mid + 1;

            }

        }

        return left;

    }

public void insert(T item) {

        if (this.size >= this.maxSize) {

            throw new IllegalStateException("The array is already full");

        }

 

        int position = findInsertionPosition(item);

 

        for (int i = size; i > position; i--) {

            this.array[i] = this.array[i - 1];

        }

        this.array[position] = item;

        size++;

    }

Copy after login

Insert Method inserts the item on its position in sorted form.

Deletion Method

1

2

3

4

5

6

7

8

9

10

11

12

public void delete(T item) {

    int index = binarySearch(item);

    if (index == -1) {

        throw new IllegalArgumentException("Unable to delete element " + item + ": the entry is not in the array");

    }

 

    for (int i = index; i < size - 1; i++) {

        this.array[i] = this.array[i + 1];

    }

    this.array[size - 1] = null;

    size--;

}

Copy after login

Search Methods

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

private int binarySearch(T target) {

        int left = 0;

        int right = size - 1;

        while (left <= right) {

            int mid = (left + right) / 2;

            int cmp = target.compareTo(this.array[mid]);

            if (cmp == 0) {

                return mid;

            } else if (cmp < 0) {

                right = mid - 1;

            } else {

                left = mid + 1;

            }

        }

        return -1;

    }

public Integer find(T target) {

        int index = binarySearch(target);

        return index == -1 ? null : index;

    }

Copy after login

Traverse Method

1

2

3

4

5

public void traverse(Callback<T> callback) {

        for (int i = 0; i < this.size; i++) {

            callback.call(this.array[i]);

        }

    }

Copy after login

Callback Interface

1

2

3

public interface Callback<T> {

        void call(T item);

    }

Copy after login

Use of Callback Interface in Traversing

1

2

3

4

5

6

public class UppercaseCallback implements UnsortedArray.Callback<String> {

    @Override

    public void call(String item) {

        System.out.println(item.toUpperCase());

    }

}

Copy after login

Unsorted Array

It is almost same from above
Initialization and getters are same.

Insertion Method

1

2

3

4

5

6

7

8

public void insert(T item) {

        if (this.size >= this.maxSize) {

            throw new IllegalStateException("The array is already full");

        } else {

            this.self[this.size] = item;

            this.size++;

        }

    }

Copy after login

Delete Method is also same

Search Method

1

2

3

4

5

6

7

8

public Integer find(T target) {

        for (int i = 0; i < this.size; i++) {

            if (this.self[i].equals(target)) {

                return i;

            }

        }

        return null;

    }

Copy after login

Dynamic Array

Dynamic Array are like array lists or lists.

Initialization

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public class DynamicArray<T> {

    private T[] array;

    private int size;

    private int capacity;

 

    @SuppressWarnings("unchecked")

    public DynamicArray(int initialCapacity) {

        if (initialCapacity <= 0) {

            throw new IllegalArgumentException("Invalid initial capacity: " + initialCapacity);

        }

        this.capacity = initialCapacity;

        this.array = (T[]) new Object[initialCapacity];

        this.size = 0;

    }

}

Copy after login

Insert Method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

private void resize(int newCapacity) {

        @SuppressWarnings("unchecked")

        T[] newArray = (T[]) new Object[newCapacity];

        for (int i = 0; i < size; i++) {

            newArray[i] = array[i];

        }

        array = newArray;

        capacity = newCapacity;

    }

    public void insert(T item) {

        if (size >= capacity) {

            resize(2 * capacity);

        }

        array[size++] = item;

    }

Copy after login

Delete Method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public void delete(T item) {

        int index = find(item);

        if (index == -1) {

            throw new IllegalArgumentException("Item not found: " + item);

        }

 

        for (int i = index; i < size - 1; i++) {

            array[i] = array[i + 1];

        }

        array[--size] = null;

        if (capacity > 1 && size <= capacity / 4) {

            resize(capacity / 2);

        }

    }

Copy after login

Everything else is same.
Hope this helps in working with arrays. Good Luck!

The above is the detailed content of Data Structures: Arrays. 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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles