[Java] Collection (1) Single column collection List

1. Collection

can dynamically save any number of objects, and provides a series of methods for operating objects: add, remove, set, get, etc. .

2. Collection framework system

Divided into two categories:

sequenceset unionbisequenceset

3.Basic introduction to List interface

The List interface is a sub-interface of the Collection interface

The elements in the List collection classordered,repeatable, supports indexing . The elements in the List container correspond to an integer serial number and can be accessed according to the serial number. Elements in the container.

Some methods for operating collection elements based on index have been added to the List collection.

1) void add(int index,Obiect ele): Insert the ele element at the index position

2) boolean addAll(int index, Collection eles): Add all elements in eles starting from the index position

3) Object get(int index): Get the element at the specified index position

4) int indexof(Obiect obi): returns the position where obi first appears in the collection

5) int lastlndexof(Obiect obi): Returns the position where obi does not appear in the current collection

6) Object remove(int index): Remove the element at the specified index position and return this element

7) Object set(int index, Object ele): Setting the element at the specified index position to ele is equivalent to replacement

8) List subList(int fromIndex, int tolndex): Returns the subcollection from fromIndex to tolndex position

example

	    List list=new ArrayList();
        //插入
        list.add(100);
        list.add(3);
        list.add("a");
         System.out.println(list);
        //删除
         list.remove(1);//默认按索引删除,索引从0开始
        list.remove(new Integer(100));//按指定元素删除,需要传入对象才行
        System.out.println(list);
        //修改
        list.set(0,"aaa");
        System.out.println(list);

Three ways to traverse List

Method 1: Use iterator

        Iterator iter=list.iterator();
        while(iter.hasNext()) {
        	Object o=iter.next();
        	System.out.println(o);
        }

Method 2: Use enhanced for

         for(Object o:list) {
        	 System.out.println(o);
         }

Method 3: Use ordinary for

         for(int i=0;i<list.size();i++) {
        	 Object o=list.get(i);
        	 System.out.println(o);
         }

4.ArrayList underlying structure and source code analysis

basic introduction:

1) ArrayList can add multiple nulls

2) ArrayList implements data storage by arrays

3) ArrayList is thread-unsafe. The reason is that the source code is not synchronized.

Source code analysis of the underlying operating mechanism of ArrayList

1) ArrayList maintains an array elementData of type Object.

transient Object[] elementData; //transient means instant, short-lived, indicating that the attribute will not be serialized

2) When creating an ArrayList object, if the no-parameter constructor is used, the initial elementData capacity is 0. For the first addition, the elementData is expanded to 10. If it needs to be expanded again, the elementData is expanded to 1.5. times.
3) If the constructor of the specified size is used, the initial elementData capacity is the specified size. If expansion is required, directly expand the elementData to 1.5 times.

5.Vector underlying structure and source code anatomy

basic introduction:

1) The bottom layer of Vector is also an object array, protected Objectl] elementData;

2) Vector is thread-synchronous, that is, thread-safe, and the operation methods of the Vector class are synchronized

//1. new Vector() 底层
/*
public Vector() {
this(10);
}
补充:如果是 Vector vector = new Vector(8);
走的方法:
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
2. vector.add(i)
2.1 //下面这个方法就添加数据到 vector 集合
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
2.2 //确定是否需要扩容 条件 : minCapacity - elementData.length>0
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
2.3 //如果 需要的数组大小 不够用,就扩容 , 扩容的算法
//newCapacity = oldCapacity + ((capacityIncrement > 0) ?
//
capacityIncrement : oldCapacity);
//就是扩容两倍.
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}

6.LinkedList underlying structure

Comprehensive description of LinkedList
1) The bottom layer of LinkedList implements the characteristics of doubly linked lists and double-ended queues

2) Any element can be added (elements can be repeated), including null

3) Threads are not safe and synchronization is not implemented

 The underlying operating mechanism of LinkedList
1) The bottom layer of LinkedList maintains a two-way linked list

2) LinkedList maintains two attributes first and last, which point to the first node and the last node respectively.

3) Each node (Node object) maintains three attributes: prev, next, and item. Prev points to the previous node, and next points to the next node. Finally realize the doubly linked list

4) Therefore, adding and deleting elements of LinkedList is not done through arrays, which is relatively more efficient.

5) Simulate a simple doubly linked list

/* 1. LinkedList linkedList = new LinkedList();
public LinkedList() {}
2. 这时 linkeList 的属性 first = null last = null
3. 执行 添加
public boolean add(E e) {
linkLast(e);
return true;
}
4.将新的结点,加入到双向链表的最后
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
*/
/* linkedList.remove(); // 这里默认删除的是第一个结点
1. 执行 removeFirst
public E remove() {
return removeFirst();
}
2. 执行
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
3. 执行 unlinkFirst, 将 f 指向的双向链表的第一个结点拿掉
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
*/

Guess you like

Origin blog.csdn.net/weixin_63357306/article/details/134369539