Vector原理讲解

一. Vector概述

本节基于JDK1.8.0_60

  1. Vector是动态数组实现的List,跟ArrayList一样,其容量能自动增长
  2. Vector是JDK1.0引入了,它的很多实现方法都加入了同步语句,因此是线程安全的
  3. Vector适用于快速访问和修改,不适用随机插入和删除
  4. Vector初始容量大小为10,扩容由初始容量和capacityIncrement共同决定
  5. Vector元素允许为null
  6. Vector现在已经基本不再使用,如果不需要线程安全的实现,推荐使用ArrayList代替Vector
  7. 源码解析:Vector源码
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable,java.io.Serializable

这里写图片描述

二. Vector总结

2.1 Vector存储结构
// 存储元素
protected Object[] elementData;

// 实际元素个数
protected int elementCount;

// 扩容时增加量,大于0增加capacityIncrement,否则翻倍
protected int capacityIncrement;

这里写图片描述

2.2 Vector初始化
// 默认实现
public Vector() {
    this(10);
}

public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}

/**
 * @param  initialCapacity   初始容量大小
 * @param  capacityIncrement 扩容增加值,大于0增加capacityIncrement,否则翻倍
 */
public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}

public Vector(Collection<? extends E> c) {
    elementData = c.toArray();
    elementCount = elementData.length;
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}
2.3 Vector扩容

Vector在每次增加元素时,都要确保足够的容量。当容量不足以容纳当前的元素个数时,就先看构造方法中传入的容量增长量参数CapacityIncrement是否为0

  1. 如果不为0,就设置新的容量为旧容量加上容量增长量
  2. 如果为0,就设置新的容量为旧的容量的2倍
  3. 如果设置后的新容量还不够,则直接新容量设置为传入的参数(也就是所需的容量)
  4. 而后同样用Arrays.copyof()方法将元素拷贝到新的数组
newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
public synchronized void ensureCapacity(int minCapacity) {
    if (minCapacity > 0) {
        modCount++;
        ensureCapacityHelper(minCapacity);
    }
}

private void ensureCapacityHelper(int minCapacity) {
    if (minCapacity - elementData.length > 0)// 需要扩容
        grow(minCapacity);
}

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    // 扩容大小?capacityIncrement : 翻倍
    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);
}

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
2.3.1 Vector一次扩容大小
int oldCapacity = elementData.length;
    // 扩容大小?capacityIncrement : 翻倍
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);

Vector扩容大小由当前元素个数oldCapacity = elementData.length与属性capacityIncrement共同决定的:
- capacityIncrement <= 0,扩容大小为oldCapacity,即翻倍
- oldCapacity > 0,扩容大小为oldCapacity的大小
这里写图片描述

2.3.2 Vector容量大小限制

JDK6及之前的版本中扩容没有限制容量大小,JDK8中限制了容量大小最大为Integer.MAX_VALU(2^31 - 1)

三. Iterator与ListIterator

JDK1.8.0_60 Vector中实现了两种迭代器Iterator:
- 子类AbstractList中实现的Iterator - Itr
- Vector中重写了子类AbstractList中的ListIterator - ListItr
Iterator只能实现顺序向后遍历,ListIterator可实现顺序向后遍历和逆向(顺序向前)遍历
Iterator只能实现remove操作,ListIterator可以实现remove操作,add操作,set操作

四. Fail-Fast机制

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

Vector也采用了快速失败的机制,通过记录modCount参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。
它是Java集合的一种错误检测机制。当多个线程对集合进行结构上的改变的操作时,有可能会产生fail-fast机制。记住是有可能,而不是一定。例如:假设存在两个线程(线程1、线程2),线程1通过Iterator在遍历集合A中的元素,在某个时候线程2修改了集合A的结构(是结构上面的修改,而不是简单的修改集合元素的内容),那么这个时候程序就会抛出 ConcurrentModificationException 异常,从而产生fail-fast机制。

五. Vector与ArrayList比较

Vector与ArrayList的最大区别就是Vector是线程安全的,而ArrayList不是线程安全的。另外区别还有:

  1. ArrayList不可以设置扩展的容量,默认1.5倍
  2. Vector可以设置扩展的容量,如果没有设置,默认2倍
  3. ArrayList的无参构造方法中初始容量为0(初次调用add()会更新为10)
  4. Vector的无参构造方法中初始容量为10
  5. Vector线程安全
  6. ArrayList线程不安全

六. Collections.synchronizedList和Vector比较

Vector是java1.0开始使用的,而集合框架从JDK1.2开始加入。
SynchronizedList和Vector最主要的区别:

  1. SynchronizedList有很好的扩展和兼容功能。他可以将所有的List的子类转成线程安全的类
  2. 使用SynchronizedList的时候,进行遍历时要手动进行同步处理
  3. SynchronizedList可以指定锁定的对象
    SynchronizedList和Vector的区别
    CopyOnWriteArrayList与Collections.synchronizedList的性能对比
package com.src.collection.list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class SynchronizedListTest {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        int len = 9000000;
        for (int i = 0; i < len; i++) {
            arrayList.add(i);
        }
        System.out.println(len + "个数据: ");
        List<Integer> list = Collections.synchronizedList(arrayList);

        long start = System.currentTimeMillis();
        for (int size = list.size(), i = 0; i < size; i++) {
            int sta = list.get(i);
        }
        System.out.println("for循环遍历耗时: " + (System.currentTimeMillis()-start) + "毫秒!");

        long second = System.currentTimeMillis();
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            int sec = iterator.next();
        }
        System.out.println("迭代器Iterator遍历耗时: " + (System.currentTimeMillis()-second) + "毫秒!");

        long third = System.currentTimeMillis();
        for (int i : list) {// 也是Iterator实现的
            int thi = i;
        }
        System.out.println("foreach循环遍历耗时: " + (System.currentTimeMillis()-third) + "毫秒!");

        long fourth = System.currentTimeMillis();
        ListIterator<Integer> listIterator = list.listIterator();
        while (listIterator.hasNext()) {
            int fou = listIterator.next();
        }
        System.out.println("迭代器ListIterator循环遍历耗时: " + (System.currentTimeMillis()-fourth) + "毫秒!");

        long firth = System.currentTimeMillis();
        list.forEach(integer -> {
            int fir = integer;
        });
        System.out.println("forEach循环遍历耗时: "+ (System.currentTimeMillis()-firth) + "毫秒!");
    }
}
9000个数据: 
for循环遍历耗时: 1毫秒!
迭代器Iterator遍历耗时: 2毫秒!
foreach循环遍历耗时: 1毫秒!
迭代器ListIterator循环遍历耗时: 3毫秒!
forEach循环遍历耗时: 84毫秒!

90000个数据: 
for循环遍历耗时: 6毫秒!
迭代器Iterator遍历耗时: 5毫秒!
foreach循环遍历耗时: 3毫秒!
迭代器ListIterator循环遍历耗时: 3毫秒!
forEach循环遍历耗时: 96毫秒!

900000个数据: 
for循环遍历耗时: 32毫秒!
迭代器Iterator遍历耗时: 21毫秒!
foreach循环遍历耗时: 13毫秒!
迭代器ListIterator循环遍历耗时: 17毫秒!
forEach循环遍历耗时: 97毫秒!

9000000个数据: 
for循环遍历耗时: 265毫秒!
迭代器Iterator遍历耗时: 33毫秒!
foreach循环遍历耗时: 35毫秒!
迭代器ListIterator循环遍历耗时: 33毫秒!
forEach循环遍历耗时: 107毫秒!

七. Vector遍历比较

package com.src.collection.list;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;

/**
 * Vector遍历效率对比
 * JDK1.8.0_60
 * */
public class VectorTest {

    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        int len = 9000;
        for (int i = 0; i < len; i++) {
            vector.add(i);
        }
        System.out.println(len + "个数据: Vector方法加了synchronized关键字!");


        long start = System.currentTimeMillis();
        for (int size = vector.size(), i = 0; i < size; i++) {
            int sta = vector.get(i);
        }
        System.out.println("for循环遍历耗时: " + (System.currentTimeMillis()-start) + "毫秒!");

        long second = System.currentTimeMillis();
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()) {
            int sec = iterator.next();
        }
        System.out.println("迭代器Iterator遍历耗时: " + (System.currentTimeMillis()-second) + "毫秒!");

        long third = System.currentTimeMillis();
        for (int i : vector) {// 也是Iterator实现的
            int thi = i;
        }
        System.out.println("foreach循环遍历耗时: " + (System.currentTimeMillis()-third) + "毫秒!");

        long fourth = System.currentTimeMillis();
        ListIterator<Integer> listIterator = vector.listIterator();
        while (listIterator.hasNext()) {
            int fou = listIterator.next();
        }
        System.out.println("迭代器ListIterator循环遍历耗时: " + (System.currentTimeMillis()-fourth) + "毫秒!");

        long firth = System.currentTimeMillis();
        vector.forEach(integer -> {
            int fir = integer;
        });
        System.out.println("forEach循环遍历耗时: "+ (System.currentTimeMillis()-firth) + "毫秒!");

        long sixth = System.currentTimeMillis();
        Enumeration<Integer> elements = vector.elements();
        while (elements.hasMoreElements()) {
            int six = elements.nextElement();
        }
        System.out.println("Enumeration循环耗时: " + (System.currentTimeMillis()-sixth) + "毫秒");
    }
}

运行结果(每次运行都有些差异):

9000个数据: Vector方法加了synchronized关键字!
for循环遍历耗时: 1毫秒!
迭代器Iterator遍历耗时: 3毫秒!
foreach循环遍历耗时: 2毫秒!
迭代器ListIterator循环遍历耗时: 2毫秒!
forEach循环遍历耗时: 75毫秒!
Enumeration循环耗时: 2毫秒

90000个数据: Vector方法加了synchronized关键字!
for循环遍历耗时: 3毫秒!
迭代器Iterator遍历耗时: 7毫秒!
foreach循环遍历耗时: 4毫秒!
迭代器ListIterator循环遍历耗时: 4毫秒!
forEach循环遍历耗时: 81毫秒!
Enumeration循环耗时: 7毫秒

900000个数据: Vector方法加了synchronized关键字!
for循环遍历耗时: 35毫秒!
迭代器Iterator遍历耗时: 34毫秒!
foreach循环遍历耗时: 33毫秒!
迭代器ListIterator循环遍历耗时: 32毫秒!
forEach循环遍历耗时: 87毫秒!
Enumeration循环耗时: 27毫秒

9000000个数据: Vector方法加了synchronized关键字!
for循环遍历耗时: 250毫秒!
迭代器Iterator遍历耗时: 258毫秒!
foreach循环遍历耗时: 256毫秒!
迭代器ListIterator循环遍历耗时: 262毫秒!
forEach循环遍历耗时: 93毫秒!
Enumeration循环耗时: 173毫秒

八. Vector源码

package java.util;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;


public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    protected Object[] elementData;

    protected int elementCount;

    protected int capacityIncrement;

    private static final long serialVersionUID = -2767605614048989439L;

    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    public Vector() {
        this(10);
    }

    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }

    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }

    public synchronized void setSize(int newSize) {
        modCount++;
        if (newSize > elementCount) {
            ensureCapacityHelper(newSize);
        } else {
            for (int i = newSize ; i < elementCount ; i++) {
                elementData[i] = null;
            }
        }
        elementCount = newSize;
    }

    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    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);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
    }

    public synchronized int capacity() {
        return elementData.length;
    }

    public synchronized int size() {
        return elementCount;
    }

    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }

    public Enumeration<E> elements() {
        return new Enumeration<E>() {
            int count = 0;

            public boolean hasMoreElements() {
                return count < elementCount;
            }

            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    public synchronized int indexOf(Object o, int index) {
        if (o == null) {
            for (int i = index ; i < elementCount ; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index ; i < elementCount ; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount-1);
    }

    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

        if (o == null) {
            for (int i = index; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    public synchronized E elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }
        return elementData(index);
    }

    public synchronized E firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }

    public synchronized void setElementAt(E obj, int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }
        elementData[index] = obj;
    }

    public synchronized void removeElementAt(int index) {
        modCount++;
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }
        else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        int j = elementCount - index - 1;
        if (j > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, j);
        }
        elementCount--;
        elementData[elementCount] = null; /* to let gc do its work */
    }

    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " > " + elementCount);
        }
        ensureCapacityHelper(elementCount + 1);
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        elementData[index] = obj;
        elementCount++;
    }

    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;

        elementCount = 0;
    }

    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
                Vector<E> v = (Vector<E>) super.clone();
            v.elementData = Arrays.copyOf(elementData, elementCount);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

    @SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
        if (a.length < elementCount)
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());

        System.arraycopy(elementData, 0, a, 0, elementCount);

        if (a.length > elementCount)
            a[elementCount] = null;

        return a;
    }

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

    public boolean remove(Object o) {
        return removeElement(o);
    }

    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    public synchronized E remove(int index) {
        modCount++;
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        E oldValue = elementData(index);

        int numMoved = elementCount - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--elementCount] = null; // Let gc do its work

        return oldValue;
    }

    public void clear() {
        removeAllElements();
    }

    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    public synchronized boolean addAll(Collection<? extends E> c) {
        modCount++;
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);
        System.arraycopy(a, 0, elementData, elementCount, numNew);
        elementCount += numNew;
        return numNew != 0;
    }

    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

    public synchronized boolean addAll(int index, Collection<? extends E> c) {
        modCount++;
        if (index < 0 || index > elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);

        int numMoved = elementCount - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        elementCount += numNew;
        return numNew != 0;
    }

    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }

    public synchronized int hashCode() {
        return super.hashCode();
    }

    public synchronized String toString() {
        return super.toString();
    }

    public synchronized List<E> subList(int fromIndex, int toIndex) {
        return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);
    }

    protected synchronized void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = elementCount - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);

        // Let gc do its work
        int newElementCount = elementCount - (toIndex-fromIndex);
        while (elementCount != newElementCount)
            elementData[--elementCount] = null;
    }

    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        final java.io.ObjectOutputStream.PutField fields = s.putFields();
        final Object[] data;
        synchronized (this) {
            fields.put("capacityIncrement", capacityIncrement);
            fields.put("elementCount", elementCount);
            data = elementData.clone();
        }
        fields.put("elementData", data);
        s.writeFields();
    }

    public synchronized ListIterator<E> listIterator(int index) {
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    public synchronized Iterator<E> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != elementCount;
        }

        public E next() {
            synchronized (Vector.this) {
                checkForComodification();
                int i = cursor;
                if (i >= elementCount)
                    throw new NoSuchElementException();
                cursor = i + 1;
                return elementData(lastRet = i);
            }
        }

        public void remove() {
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.remove(lastRet);
                expectedModCount = modCount;
            }
            cursor = lastRet;
            lastRet = -1;
        }

        @Override
        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            synchronized (Vector.this) {
                final int size = elementCount;
                int i = cursor;
                if (i >= size) {
                    return;
                }
                @SuppressWarnings("unchecked")
                final E[] elementData = (E[]) Vector.this.elementData;
                if (i >= elementData.length) {
                    throw new ConcurrentModificationException();
                }
                while (i != size && modCount == expectedModCount) {
                    action.accept(elementData[i++]);
                }
                // update once at end of iteration to reduce heap write traffic
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    final class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        public boolean hasPrevious() {
            return cursor != 0;
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor - 1;
        }

        public E previous() {
            synchronized (Vector.this) {
                checkForComodification();
                int i = cursor - 1;
                if (i < 0)
                    throw new NoSuchElementException();
                cursor = i;
                return elementData(lastRet = i);
            }
        }

        public void set(E e) {
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.set(lastRet, e);
            }
        }

        public void add(E e) {
            int i = cursor;
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.add(i, e);
                expectedModCount = modCount;
            }
            cursor = i + 1;
            lastRet = -1;
        }
    }

    @Override
    public synchronized void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int elementCount = this.elementCount;
        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final int size = elementCount;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            elementCount = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = elementCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    @SuppressWarnings("unchecked")
    @Override
    public synchronized void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, elementCount, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    @Override
    public Spliterator<E> spliterator() {
        return new VectorSpliterator<>(this, null, 0, -1, 0);
    }

    /** Similar to ArrayList Spliterator */
    static final class VectorSpliterator<E> implements Spliterator<E> {
        private final Vector<E> list;
        private Object[] array;
        private int index; // current index, modified on advance/split
        private int fence; // -1 until used; then one past last index
        private int expectedModCount; // initialized when fence set

        /** Create new spliterator covering the given  range */
        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
                          int expectedModCount) {
            this.list = list;
            this.array = array;
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        private int getFence() { // initialize on first use
            int hi;
            if ((hi = fence) < 0) {
                synchronized(list) {
                    array = list.elementData;
                    expectedModCount = list.modCount;
                    hi = fence = list.elementCount;
                }
            }
            return hi;
        }

        public Spliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null :
                new VectorSpliterator<E>(list, array, lo, index = mid,
                                         expectedModCount);
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super E> action) {
            int i;
            if (action == null)
                throw new NullPointerException();
            if (getFence() > (i = index)) {
                index = i + 1;
                action.accept((E)array[i]);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi; // hoist accesses and checks from loop
            Vector<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null) {
                if ((hi = fence) < 0) {
                    synchronized(lst) {
                        expectedModCount = lst.modCount;
                        a = array = lst.elementData;
                        hi = fence = lst.elementCount;
                    }
                }
                else
                    a = array;
                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
                    while (i < hi)
                        action.accept((E) a[i++]);
                    if (lst.modCount == expectedModCount)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        public long estimateSize() {
            return (long) (getFence() - index);
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
}
  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
体感算法的数学原理主要分为两个部分,一是运动跟踪,二是动作识别。其中,运动跟踪主要是通过计算机视觉技术来进行的,包括图像处理、目标检测、特征提取等过程。动作识别则是通过机器学习算法来实现的,主要包括分类器的训练和分类器的应用两个过程。 在运动跟踪方面,常用的算法有基于颜色模型的跟踪算法、基于特征点匹配的跟踪算法、基于光流的跟踪算法等。其中,基于颜色模型的跟踪算法是最简单的一种,其原理是通过对目标物体的颜色进行建模,然后在后续的图像中寻找和目标物体颜色模型最相似的像素块来跟踪目标物体。 以下是基于颜色模型的跟踪算法的C语言代码示例: ```c // 输入参数为当前帧图像和目标物体的颜色模型 // 输出参数为目标物体的位置坐标 void colorTracking(Mat frame, Mat model, Point& target) { // 定义颜色阈值 Scalar lower(0, 0, 0); Scalar upper(255, 255, 255); // 对当前帧图像进行颜色分割 Mat hsv, mask; cvtColor(frame, hsv, COLOR_BGR2HSV); inRange(hsv, lower, upper, mask); // 对颜色分割结果进行形态学操作 Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(5, 5)); morphologyEx(mask, mask, MORPH_CLOSE, kernel); // 寻找最大轮廓 vector<vector<Point>> contours; findContours(mask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); if (contours.size() > 0) { int maxIdx = -1, maxArea = 0; for (int i = 0; i < contours.size(); i++) { int area = contourArea(contours[i]); if (area > maxArea) { maxArea = area; maxIdx = i; } } // 计算目标物体的位置 if (maxIdx >= 0) { Rect rect = boundingRect(contours[maxIdx]); target.x = rect.x + rect.width / 2; target.y = rect.y + rect.height / 2; } } } ``` 在动作识别方面,常用的算法有基于决策树的分类算法、基于支持向量机的分类算法、基于深度学习的分类算法等。其中,基于决策树的分类算法是最简单的一种,其原理是通过对训练样本进行特征提取和分类标注,然后构建一个决策树模型来实现动作识别。 以下是基于决策树的分类算法的C语言代码示例: ```c // 定义决策树节点 struct DTreeNode { int featureIdx; // 特征索引 float threshold; // 划分阈值 int leftChild; // 左子树节点索引 int rightChild; // 右子树节点索引 int label; // 叶子节点标签 }; // 定义决策树模型 class DTree { public: DTree() {} ~DTree() {} // 决策树训练函数 void train(Mat& features, Mat& labels) { // TODO: 实现决策树训练算法 } // 决策树分类函数 int predict(Mat& feature) { // TODO: 实现决策树分类算法 return -1; } private: vector<DTreeNode> nodes; // 决策树节点 }; ``` 以上是体感算法的数学原理和C语言代码示例,希望能对您有所帮助。需要注意的是,体感算法是一个较为复杂的领域,其中涉及到的数学原理和算法也较为复杂,请在实际应用中进行深入研究和实践。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值