java simple parsing ArrayList Iterable

Article directory

Implement stack and queue in Java, and check java source code

Dynamic array containerarraylist (generic container)

1. For the main methods, we will not elaborate here

2. Basic principles

  1. For the basic principle, it is similar to dynamic array
public class DynamicArray<E> {
    private static final int DEFAULT_CAPACITY = 10;
    private int size;
    private Object[] elementData;
    public DynamicArray(){
        this.elementData = new Object[DEFAULT_CAPACITY];
    *  First, make sure that space is satisfied
    * @param minCapacity
    private void ensureCapacity(int minCapacity){
        int oldCapacity = elementData.length;
        if (oldCapacity >= minCapacity){
        int newCapacity = oldCapacity * 2;
        if (newCapacity < minCapacity){
            newCapacity = minCapacity;
        elementData = Arrays.copyOf(elementData,newCapacity);
    public void  add(E e){
        ensureCapacity(size +1);
        elementData[size++] = e;
    public E get(int index){
        return (E)elementData[index];
    public int size(){
        return size;
    public E set(int index,E element){
        E oldValue = get(index);
        elementData[index] = element;
        return oldValue;

3. The interface of ArrayList implements iterative interface

  1. With the implementation of iteration, you can use a more simplified foreach syntax,
  2. iterable is different from iterator,
    1. Iterable means that the object can be iterated. It has a method iterator that returns the iterator object. In fact, it traverses the methods of the iterator interface
    2. If the object implements iterable, you can create foreach syntax
    3. Class can either not implement iterable or create an iterator object
  3. Iterative trapping
    1. It is not possible to call the container deletion method in the iteration process.
      public void remove(ArrayList<Integer> list){
         for(Integer a :list){
          if(a <= 100){
    2. But if you change it to this way, you won't make a mistake
             public void remove(ArrayList<Integer> list){
                 for(Integer a :list){
                  if(a <= 100){
    3. The iterative principle of ArrayList
          public ListIterator<E> listIterator(int index) {
              if (index < 0 || index > size)
                  throw new IndexOutOfBoundsException("Index: "+index);
              return new ListItr(index);
    4. Using iterators to express the idea of separation of concerns, separating the actual organization of data from the iterative traversal of data, which is a common design pattern

Keywords: Java

Added by barrow on Sat, 23 Nov 2019 19:59:59 +0200