Maison > Java > javaDidacticiel > le corps du texte

Structures de données : tableaux

王林
Libérer: 2024-08-11 20:35:32
original
1124 Les gens l'ont consulté

Data Structures: Arrays

Tableau statique

Un tableau est une structure de données linéaire où tous les éléments sont disposés séquentiellement. Il s'agit d'une collection d'éléments du même type de données stockés à des mémoire contiguë emplacements.

Initialisation

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];
        }
    }
}
Copier après la connexion

Dans Core Array Class, nous allons stocker la taille du tableau et un squelette général pour l'initialisation du tableau. Dans le constructeur, nous demandons la taille du tableau, créons un objet et le transposons dans le tableau souhaité.

Définir la méthode

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;
        }
    }
Copier après la connexion

Cette méthode demande qu'un élément soit stocké dans un tableau et un index sur lequel l'élément doit être stocké.

Obtenir la méthode

public T get(int index) {
        if (index >= this.size || index < 0) {
            throw new IndexOutOfBoundsException("Index Out of bounds");
        } else {
            return self[index];
        }
    }
Copier après la connexion

La méthode Get demande un index et récupère l'élément de cet index.

Méthode d'impression

public void print() {
        for (int i = 0; i < size; i++) {
            System.out.println(this.self[i]+" ");
        }
    }
Copier après la connexion

La méthode d'impression consiste simplement à imprimer tous les membres d'un tableau sur une seule ligne avec un espace séparant chaque élément entre eux.

Tableau trié

Des tableaux mais ayant une fonctionnalité pour trier les éléments lui-même.

Initialisation

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;
    }
}
Copier après la connexion

Dans la classe Tableau trié, nous allons stocker la taille du tableau et demander également la taille maximale du tableau ainsi qu'un squelette général pour l'initialisation du tableau. Dans le constructeur, nous demandons la taille maximale du tableau, créons un objet et le transposons dans le tableau souhaité.

Getteurs

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];
    }
Copier après la connexion

Méthode d'insertion

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++;
    }
Copier après la connexion

La méthode Insert insère l'élément à sa position sous forme triée.

Méthode de suppression

    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--;
    }
Copier après la connexion

Méthodes de recherche

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;
    }
Copier après la connexion

Méthode de parcours

public void traverse(Callback<T> callback) {
        for (int i = 0; i < this.size; i++) {
            callback.call(this.array[i]);
        }
    }
Copier après la connexion

Interface de rappel

public interface Callback<T> {
        void call(T item);
    }
Copier après la connexion

Utilisation de l'interface de rappel dans le parcours

public class UppercaseCallback implements UnsortedArray.Callback<String> {
    @Override
    public void call(String item) {
        System.out.println(item.toUpperCase());
    }
}
Copier après la connexion

Tableau non trié

C'est presque pareil vu d'en haut
L'initialisation et les getters sont identiques.

Méthode d'insertion

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++;
        }
    }
Copier après la connexion

La méthode de suppression est également la même

Méthode de recherche

public Integer find(T target) {
        for (int i = 0; i < this.size; i++) {
            if (this.self[i].equals(target)) {
                return i;
            }
        }
        return null;
    }
Copier après la connexion

Tableau dynamique

Les tableaux dynamiques sont comme des listes de tableaux ou des listes.

Initialisation

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;
    }
}
Copier après la connexion

Méthode d'insertion

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;
    }
Copier après la connexion

Supprimer la méthode

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);
        }
    }
Copier après la connexion

Tout le reste est pareil.
J'espère que cela vous aidera à travailler avec des tableaux. Bonne chance !

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!