• Java-数据结构-ArrayList


     1 import java.util.Iterator;
     2 import java.util.NoSuchElementException;
     3 
     4 public class ArrayList<E> implements Iterable<E> {
     5     private final int INITIAL_CAPACITY = 50;
     6     private int count;
     7     private E[] data;
     8 
     9     public ArrayList() {
    10         count = 0;
    11         data = (E[]) new Object[INITIAL_CAPACITY];
    12     }
    13 
    14     public Iterator<E> iterator() {
    15         return new ArrayListIterator<E>(this);
    16     }
    17 
    18     private class ArrayListIterator<E> implements Iterator<E> {
    19         // fields to store state
    20         private ArrayList<E> list;// reference to the list it is iterating down
    21         private int nextIndex = 0; // the index of the next value to return
    22         private boolean canRemove = false;
    23 
    24         private ArrayListIterator(ArrayList<E> list) {
    25             this.list = list;
    26         }
    27 
    28         public boolean hasNext() {
    29             return (nextIndex < list.count);
    30         }
    31 
    32         public E next() {
    33             if (nextIndex >= list.count) throw new NoSuchElementException();
    34             canRemove = true;               //← for the remove method
    35             return list.get(nextIndex++);   //← increment and return
    36         }
    37 
    38         public void remove() {
    39             if (!canRemove) throw new IllegalStateException();
    40             canRemove = false;
    41             nextIndex--;
    42             list.remove(nextIndex);
    43         }
    44     }
    45 
    46     public E get(int index) {
    47         return data[index];
    48     }
    49 
    50     public void add(E item) {
    51         data[count++] = item;
    52     }
    53 
    54     public void remove(int index) {
    55         for (int i = index; i < count; i++)
    56             data[i] = data[i + 1];
    57         data[--count] = null;
    58     }
    59 
    60     public void remove() {
    61         remove(count - 1);
    62     }
    63 
    64 }
    ~~Jason_liu O(∩_∩)O
  • 相关阅读:
    sql优化
    多字段in
    最大值对应的行数据
    spring boot admin
    git + idea 操作
    css 多行溢出显示省略号失效
    Android输入系统(7)——Linux input子系统代码分析与调试 Hello
    Java中的正则表达式 Hello
    mybatis 中文路径报错处理
    React 18 之 useTransition
  • 原文地址:https://www.cnblogs.com/JasonCow/p/14846687.html
Copyright © 2020-2023  润新知