Condivisione della tecnologia

[Struttura dati Java] Una delle prime tabelle lineari: tabella sequenziale

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Semplice implementazione di una tabella di sequenza utilizzando Java

Una tabella di sequenza è una struttura lineare che utilizza un'unità di archiviazione con un indirizzo fisico continuo per archiviare elementi di dati in sequenza. Generalmente viene utilizzata l'archiviazione su array. Completare l'aggiunta, la cancellazione, il controllo e la modifica dei dati sull'array.

Le tabelle lineari generalmente includono i seguenti metodi:

classe pubblica MyArrayList {
array privato int[];
dimensione int privata;
   //Il metodo di costruzione predefinito alloca lo spazio per impostazione predefinita
ElencoSeq(){ }
    // Imposta la capacità sottostante della tabella di sequenza sulla capacità specificata
SeqList(int capacitàinizializzazione){ }

   // Aggiunge nuovi elementi, per impostazione predefinita vengono aggiunti alla fine dell'array
pubblico void add(int dati) { }
    //Aggiungi l'elemento alla posizione pos
pubblico void add(int pos, int data) { }
   // Determina se un elemento è contenuto
booleano pubblico contiene(int toFind) { restituisce true; }
    // Trova la posizione corrispondente a un elemento
pubblico int indexOf(int toFind) { restituisci -1; }
    // Ottiene l'elemento nella posizione pos
pubblico int get(int pos) { ritorno -1; }
   // Imposta l'elemento nella posizione pos su valore
pubblico void set(int pos, int valore) { }
    //Elimina la prima occorrenza della chiave della parola chiave
pubblico void remove(int toRemove) { }
   // Ottiene la lunghezza della tabella di sequenza
pubblico int size() { restituisci 0; }
    //Cancella la tabella delle sequenze
pubblico void clear() { }
   
   //Stampa la tabella delle sequenze
visualizzazione pubblica vuota() { }
}

Successivamente, implementa una tabella di sequenza di tipo int secondo il metodo sopra:

  1. import java.util.Arrays;
  2. public class MyArrayList {
  3. private int[] elem;
  4. private int usedSize;
  5. private static final int DEFAULT_SIZE = 10;
  6. public MyArrayList(){
  7. elem = new int[DEFAULT_SIZE];
  8. }
  9. public MyArrayList(int initCapacity){
  10. elem = new int[initCapacity];
  11. }
  12. private boolean checkCapacity(){
  13. if(this.usedSize == elem.length){
  14. return true;
  15. }
  16. return false;
  17. }
  18. public void display(){
  19. for (int i = 0; i < this.usedSize; i++) {
  20. System.out.print(this.elem[i] + " ");
  21. }
  22. }
  23. public void add(int data){
  24. if(checkCapacity()){
  25. this.elem = Arrays.copyOf(this.elem,2*elem.length);
  26. }
  27. this.elem[this.usedSize] = data;
  28. this.usedSize++;
  29. return;
  30. }
  31. public void add(int pos,int data){
  32. if(pos > this.usedSize || pos < 0){
  33. throw new PosOutOfBoundsException("插入位置错误!");
  34. }
  35. if(checkCapacity()){
  36. this.elem = Arrays.copyOf(this.elem,2*elem.length);
  37. }
  38. for (int i = this.usedSize - 1; i >=pos ; i--) {
  39. elem[i+1] = elem[i];
  40. }
  41. this.elem[pos] = data;
  42. this.usedSize++;
  43. return;
  44. }
  45. public boolean contains(int data){
  46. for (int i = 0; i < this.usedSize; i++) {
  47. if(this.elem[i] == data){
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. public int indexof(int data){
  54. for (int i = 0; i < this.usedSize; i++) {
  55. if(this.elem[i] == data){
  56. return i;
  57. }
  58. }
  59. return -1;
  60. }
  61. public int get(int pos){
  62. if(pos >= this.usedSize || pos < 0){
  63. throw new PosOutOfBoundsException("输入的位置错误!");
  64. }
  65. return this.elem[pos];
  66. }
  67. public void set(int pos,int data){
  68. if(pos >= this.usedSize || pos < 0){
  69. throw new PosOutOfBoundsException("输入的位置错误!");
  70. }
  71. this.elem[pos] = data;
  72. }
  73. public int size(){
  74. return this.usedSize;
  75. }
  76. public void remove(int data){
  77. if(this.contains(data)){
  78. int pos = this.indexof(data);
  79. for (int i = pos; i < this.usedSize - 1; i++) {
  80. this.elem[pos] = this.elem[pos+1];
  81. }
  82. this.usedSize--;
  83. }else{
  84. throw new PosOutOfBoundsException("没有该元素");
  85. }
  86. }
  87. public void clear(){
  88. this.usedSize = 0;
  89. return;
  90. }
  91. }

Introduzione a ArrayList

Nel framework della raccolta, ArrayList è una classe ordinaria che implementa l'interfaccia List. Il diagramma del framework specifico è il seguente:

  • ArrayList è implementato in modo generico e deve essere istanziato prima dell'uso.
  • ArrayList implementa l'interfaccia RandomAccess, indicando che ArrayList supporta l'accesso casuale
  • ArrayList implementa l'interfaccia Cloneable, indicando che ArrayList può essere clonato
  • ArrayList implementa l'interfaccia Serializable, indicando che ArrayList supporta la serializzazione
  • A differenza di Vector, ArrayList non è thread-safe e può essere utilizzato in un singolo thread. In multithread è possibile scegliere Vector o
  • Copia su scrittura array elenco
  • Il livello inferiore di ArrayList è uno spazio continuo e può essere espanso dinamicamente. È un elenco di sequenze di tipo dinamico.

Come utilizzare ArrayList

Costruttore ArrayList

Metodo costruttore in ArrayList:

ArrayList(); //Nessuna costruzione di parametri

ArrayList(Collezione<? extends E> c); //Utilizza altre raccolte per creare ArrayList

ArrayList(int partialCapacity); //Specifica la capacità iniziale della tabella di sequenza

Esempio di codice:

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list1 = new ArrayList<>();//无参构造
  4. List<Integer> list2 = new ArrayList<>(10);//指定容量
  5. list2.add(1);
  6. list2.add(2);
  7. list2.add(3);
  8. List<Integer> list3 = new ArrayList<>(list2);//利用其他 Collection 构建 ArrayList
  9. }
  10. }

Operazioni comuni su ArrayList

tappo di coda

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();//无参构造
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. System.out.println(list);
  8. }
  9. }

Inserisci l'elemento nella posizione specificata

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. list.add(1,4);
  8. System.out.println(list);
  9. }
  10. }

Termina inserire elementi da un altro elenco di sequenze

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list1 = new ArrayList<>();
  4. list1.add(4);
  5. list1.add(5);
  6. list1.add(6);
  7. List<Integer> list = new ArrayList<>();
  8. list.add(1);
  9. list.add(2);
  10. list.add(3);
  11. list.addAll(list1);
  12. System.out.println(list);
  13. }
  14. }

Elimina l'elemento nella posizione specificata

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. list.remove(1);
  8. System.out.println(list);
  9. }
  10. }

Elimina i dati specificati

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. list.remove(new Integer(2));
  8. System.out.println(list);
  9. }
  10. }

Ottieni l'elemento nella posizione specificata

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. System.out.println(list.get(1));
  8. }
  9. }

Imposta l'elemento nella posizione specificata su nuovi dati

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. list.set(1,4);
  8. System.out.println(list);
  9. }
  10. }

Cancella elenco sequenze

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. list.clear();
  8. System.out.println(list);
  9. }
  10. }

Determina se un elemento è nell'elenco della sequenza

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. System.out.println(list.contains(2));
  8. System.out.println(list.contains(4));
  9. }
  10. }

Restituisce l'indice del primo elemento specificato

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. list.add(1);
  8. System.out.println(list.indexOf(1));
  9. }
  10. }

Restituisce l'indice dell'ultimo elemento specificato

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. list.add(1);
  8. System.out.println(list.lastIndexOf(1));
  9. }
  10. }

Intercetta parte della lista

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. System.out.println(list.subList(0,2));
  8. }
  9. }

Tre modi per attraversare ArrayList

ArrayList può essere attraversato in tre modi: ciclo for + pedice, ciclo potenziato foreach e utilizzo di iteratori

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1);
  5. list.add(2);
  6. list.add(3);
  7. //使用fori遍历
  8. for (int i = 0; i < list.size(); i++) {
  9. System.out.print(list.get(i));
  10. }
  11. System.out.println();
  12. //使用foreach遍历
  13. for(Integer integer:list){
  14. System.out.print(integer);
  15. }
  16. System.out.println();
  17. //使用迭代器遍历
  18. Iterator<Integer> it = list.listIterator();
  19. while(it.hasNext()){
  20. System.out.print(it.next());
  21. }
  22. }
  23. }

risultato dell'operazione:

Utilizzo dello scenario di ArrayList

Algoritmo di mescolamento

Mescola un mazzo di carte da gioco in modo casuale e distribuiscilo a tre persone, ciascuna con cinque carte.

La posizione del codice originale dell'algoritmo:

shufflecards · Esempi classici di Always Freshwater Fish/Java - Code Cloud - Open Source Cina (gitee.com)

Triangolo Yang Hui

Descrizione argomento:

Codice:

  1. public class Test {
  2. public static List<List<Integer>> generate(int numRows) {
  3. List<List<Integer>> list = new LinkedList<>();
  4. for (int i = 0; i < numRows; i++) {
  5. List<Integer> row = new LinkedList<>();
  6. for (int j = 0; j < i + 1; j++) {
  7. if (j == 0 || i == j) {
  8. row.add(1);
  9. } else {
  10. row.add(list.get(i - 1).get(j - 1) + list.get(i - 1).get(j));
  11. }
  12. }
  13. list.add(row);
  14. }
  15. return list;
  16. }
  17. public static void main(String[] args) {
  18. Scanner scanner = new Scanner(System.in);
  19. int numRows = scanner.nextInt();
  20. List<List<Integer>> list = generate(numRows);
  21. for (int i = 0; i < numRows; i++) {
  22. for (int j = 0; j < i + 1; j++) {
  23. System.out.print(list.get(i).get(j) + " ");
  24. }
  25. System.out.println();
  26. }
  27. }
  28. }

Grafico dei risultati in esecuzione: