java simple parsing ArrayList Iterable
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
- 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];
}
private void ensureCapacity(int minCapacity){
int oldCapacity = elementData.length;
if (oldCapacity >= minCapacity){
return;
}
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
- With the implementation of iteration, you can use a more simplified foreach syntax,
-
iterable is different from iterator,
- 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
- If the object implements iterable, you can create foreach syntax
- Class can either not implement iterable or create an iterator object
- Iterative trapping
- 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){
list.remove(a);
}
}
}
- 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){
list.remove();
}
}
}
- 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);
}
- 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