欢迎使用CSDN-markdown编辑器

来源:互联网 发布:linux强制删除文件夹 编辑:程序博客网 时间:2024/05/29 13:21

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.Vector;

import javax.xml.stream.events.Namespace;

/**
* 主要三种类型的集合,集合只存储引用
* 集(set),序列(sequence),映射(map )
*/
/**
* 集
*
* 无序排列,集中不能有重复对象
* /
/**
* 序列
* 有两个子群 列表(向量、链表、栈),队列
*
* 所有序列和集都实现了Iterable、collection接口,即有迭代器
*
* /

/**
*
* 使用向量Vector定义了元素为T的序列集合
* (所有的集合类存储的都是对象的引用)
*
* public class Vectorextends AbstractList
* implements List,RandomAccess, Cloneable, java.io.Serializable
* 实现了List接口,可以当做列表来使用
*
*
* 一、向量的容量和长度
* 容量
* 1.获取容量
* int namesMax=names.capacity();获取当前容量
* 2.确保容量
* names.ensureapacity(150);若容量不足150,自动扩展150
* 长度
* 1.获取长度
* public synchronized int size() {
return elementCount;
}
//所以向量的长度即为元素的个数
* names.size();获取向量中元素的个数
* int freeCount=names.capacity()-names.size();以此获得空闲空间的空间大小
* 2.设置长度
* names.setSize(50);如果不足50个,不足的部分全部引用值为空,超过50的值会被丢弃掉。
* 如果这些对象还有其他引用,对象仍有效
* 3.自适应长度
* names.trimToSize(); 如果容量比长度大,就将容量适应长度,缩小容量
* 二、存对象
*
* 1.names.add(a);
* 将a的引用直接存到names的后面,且向量的长度加1
* 2.names.add(2,a);
* 将a插入位置为2的地方,2及后面的引用依次后移
* 如果索引值大于向量的长度抛出ArrayIndexOutOfBoundsException异常
* 意味着,你目前只有一个元素,你要新加一个元素到第3个位置上。
* 3.names.set(2,a);
* 将位置为2的引用替换为a
* 4.names.addAll(myNameList)
* 将集合对象插入到已存对象的后面
* 4.names.addAll(i,myNameList)
* 将集合对象插入到i开始的一段空间,i及以后都后移
*
*
* 三、查找对象
*
* 1.由索引值查找
* String name=name.get(2);
* 获取向量中的第五个元素,若非法索引抛出ArrayIndexOutOfBoundsException异常
* 2.获取第一个元素
* String name2=names.firstElement();
* //如果元素为0,则抛出NoSuchElementException异常
* public synchronized E firstElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(0);
}
* String name2=names.lastElement();
* 3.利用迭代器访问向量中的元素
* 1.
* java.util.Iterator iter=names.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
System.out.println(iter.toString());
}
2.
ListIterator list=names.listIterator();//获取所有的对象
while (list.hasNext()) {
System.out.println(list.next());
System.out.println(iter.toString());
}
3.ListIterator list=names.listIterator(2);//获取从索引值为2开始的所有的对象
4.List list=names.subList(2,5);//获取索引为2,3,4
5.ListIterator listIter=names..subList(2,5).listIterator(2);
//获取从names索引值为2,3,4的对象,再从这个集合里面获取索引为2开始的所有的值
*4.提取所有的元素,以数组的形式输出
* String[] data =names.toArray(new String[names.size]);
*四、删除元素
* 1.names.remove(0);是没有返回值,直接删除,
* 2.String name=names.remove(0);//2.返回删除的对象,
* 3.boolean delete =names.remove(name);//删除第一个name的引用,如果找到了就是true,否则返回false
* 4.names.removeAll(names.subList(2,5);//删除names中2到4索引元素,以及这些元素的副本?
* 5.names.retainAll(names.subList(2,5)//保留2到4索引的元素
* 该方法返回一个boolean值,至少一个元素被删除,则返回true,如果实参为null则抛出NullPointerException异常
* NullPointerException if this vector contains one or more null
* elements and the specified collection does not support null
* elements
6.names.removeAllElements();//移除所有元素
for (int i = 0; i < elementCount; i++)
elementData[i] = null;
elementCount = 0;//不仅将元素设为了空,还将elementCount 设置为 0
要清空Vector<>对象,必须真正删除其中的元素,而不是将元素设为null
7.Vector.isEmpty();
public synchronized boolean isEmpty() {
return elementCount == 0;
}
//通过判断elementCount的数目来确定是否被清空
**/
public class TrySimpleVector {

public static void main(String[] args) {    // TODO Auto-generated method stub   /**      *   public Vector() {    *       this(10);    *   }      * Constructs an empty vector so that its internal data array      * has size {@code 10} and its standard capacity increment is      * zero.      *       */    Vector<String> transaction=new Vector<>();    //默认的构造函数是创建一个空向量,其容量为10个对象,一旦装满扩大一倍     /**      *       * public Vector(int initialCapacity) {      *     this(initialCapacity, 0);      * }type filter text      * Constructs an empty vector with the specified initial capacity and      * with its capacity increment equal to zero.      *      * @param   initialCapacity   the initial capacity of the vector      * @throws IllegalArgumentException if the specified initial capacity      *         is negative      *       *       */    Vector<String> transaction1=new Vector<>(100);    //初始化100个字符串,每次超过增加一倍    /**     *      *      *  public Vector(int initialCapacity, int capacityIncrement) {            super();            if (initialCapacity < 0)                throw new IllegalArgumentException("Illegal Capacity: "+                                               initialCapacity);            this.elementData = new Object[initialCapacity];            this.capacityIncrement = capacityIncrement;        }     * Constructs an empty vector with the specified initial capacity and     * capacity increment.     *     * @param   initialCapacity     the initial capacity of the vector//初始容量     * @param   capacityIncrement   the amount by which the capacity is//增量     *                              increased when the vector overflows     * @throws IllegalArgumentException if the specified initial capacity     *         is negative//可能会抛出上面的错误,当初始值是不合法时     */    Vector<String> transaction2=new Vector<>(100,10);    //初始化100,每次超过增加10个    Vector<String> names=new Vector<>();    String[] firstnames={"Jack","Jill","bill","jksbd"};//注意是数组记得加[]    for (String string : firstnames) {        names.add(string);    }    /**     *      * public synchronized int capacity() {        return elementData.length;    }     * Returns the current capacity of this vector.//返回当前向量的容量     *     * @return  the current capacity (the length of its internal     *          data array, kept in the field {@code elementData}     *          of this vector)     */    int namesMax=names.capacity();      /**       *        *        *        *  public synchronized void ensureCapacity(int minCapacity) {                if (minCapacity > 0) {                modCount++;                ensureCapacityHelper(minCapacity);            }        }     * Increases the capacity of this vector, if necessary, to ensure     * that it can hold at least the number of components specified by     * the minimum capacity argument.     *     * <p>If the current capacity of this vector is less than     * {@code minCapacity}, then its capacity is increased by replacing its     * internal data array, kept in the field {@code elementData}, with a     * larger one.  The size of the new data array will be the old size plus     * {@code capacityIncrement}, unless the value of     * {@code capacityIncrement} is less than or equal to zero, in which case     * the new capacity will be twice the old capacity; but if this new size     * is still smaller than {@code minCapacity}, then the new capacity will     * be {@code minCapacity}.     *     * @param minCapacity the desired minimum capacity     */    names.ensureCapacity(150);     /*     * 获得第向量的长度,即为元素的个数     */     /**      *  public synchronized int size() {                return elementCount;         }     * Returns the number of components in this vector.//返回向量中元素的个数     *     * @return  the number of components in this vector     */    int freeCount=names.capacity()-names.size();    /**     *     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;            }     *      * Sets the size of this vector. If the new size is greater than the     * current size, new {@code null} items are added to the end of     * the vector. If the new size is less than the current size, all     * components at index {@code newSize} and greater are discarded.     *     * @param  newSize   the new size of this vector     * @throws ArrayIndexOutOfBoundsException if the new size is negative     */

// names.setSize(50);
/**
*
* public synchronized void trimToSize() {
modCount++;
int oldCapacity = elementData.length;
if (elementCount < oldCapacity) {
elementData = Arrays.copyOf(elementData, elementCount);
}
}
* Trims the capacity of this vector to be the vector’s current
* size. If the capacity of this vector is larger than iJill
billts current
* size, then the capacity is changed to equal the size by replacing
* its internal data array, kept in the field {@code elementData},
* with a smaller one. An application can use this operation to
* minimize the storage of a vector.
*
*
* 如果容量比长度大,就将容量适应长度,缩小容量
*/
names.trimToSize();

      /**       *   public synchronized E get(int index) {                if (index >= elementCount)                    throw new ArrayIndexOutOfBoundsException(index);                return elementData(index);            }     * Returns the element at the specified position in this Vector.     *     * @param index index of the element to return     * @return object at the specified index     * @throws ArrayIndexOutOfBoundsException if the index is out of range     *            ({@code index < 0 || index >= size()})     * @since 1.2     */    String name1=names.get(2);     /*     * 获得第一个元素     */     /**   public synchronized E firstElement() {                if (elementCount == 0) {                    throw new NoSuchElementException();                }                return elementData(0);            }     * Returns the first component (the item at index {@code 0}) of     * this vector.     *     * @return     the first component of this vector     * @throws NoSuchElementException if this vector has no components     */    String name2=names.firstElement();    String name=names.remove(0);     /**     *   public synchronized boolean retainAll(Collection<?> c) {            return super.retainAll(c);            }//返回一个boolean     *      * Retains only the elements in this Vector that are contained in the     * specified Collection.  In other words, removes from this Vector all     * of its elements that are not contained in the specified Collection.     *     * @param c a collection of elements to be retained in this Vector     *          (all other elements are removed)     * @return true if this Vector changed as a result of the call     * @throws ClassCastException if the types of one or more elements     *         in this vector are incompatible with the specified     *         collection     * (<a href="Collection.html#optional-restrictions">optional</a>)     * @throws NullPointerException if this vector contains one or more null     *         elements and the specified collection does not support null     *         elements     *         (<a href="Collection.html#optional-restrictions">optional</a>),     *         or if the specified collection is null     * @since 1.2     */    names.retainAll(names.subList(2,5));    /*     * 移除所有元素     */     /**       *   public synchronized void removeAllElements() {                modCount++;                // Let gc do its work                for (int i = 0; i < elementCount; i++)                elementData[i] = null;                elementCount = 0;//不仅将元素设为了空,还将elementCount 设置为 0            }     * Removes all components from this vector and sets its size to zero.     *     * <p>This method is identical in functionality to the {@link #clear}     * method (which is part of the {@link List} interface).     */    names.removeAllElements();     /*     * 判断元素是否为空     */    /**     *   public synchronized boolean isEmpty() {            return elementCount == 0;    }     *      * Tests if this vector has no components.     *     * @return  {@code true} if and only if this vector has     *          no components, that is, its size is zero;     *          {@code false} otherwise.     */    names.isEmpty();    /**     * 访问元素1     * 所有序列的集合都实现了Iterablle接口,所以可以使用collection-base for进行元素访问     *      */    for (String name0 : names) {        System.out.println(name);    }    /*     * 访问元素2     * 使用迭代器来实现     * hasNext()返回boolean值     * 调用iter.next()方法后,返回一个String类型的值     * 而且iter也变成了next     * Jack        java.util.Vector$Itr@385715     */    java.util.Iterator<String> iter=names.iterator();    while (iter.hasNext()) {        System.out.println(iter.next());        System.out.println(iter.toString());    }    ListIterator<String> list=names.listIterator();    while (list.hasNext()) {        System.out.println(list.next());        System.out.println(iter.toString());    }    List<String> list1=names.subList(1,3);    for (String string : list1) {        System.out.println(string);    }           /*     * 访问元素3     * 使用get方法访问元素,返回方法实参指定的索引位置上的引用     * 其以0为起始点的索引     * firstnames.length\names.size()     */    /**     *      *      *  public synchronized E get(int index) {            if (index >= elementCount)            throw new ArrayIndexOutOfBoundsException(index);            return elementData(index);        }     * Returns the element at the specified position in this Vector.     *     * @param index index of the element to return     * @return object at the specified index     * @throws ArrayIndexOutOfBoundsException if the index is out of range     *            ({@code index < 0 || index >= size()})     * @since 1.2     */    for (int i = 0; i < names.size(); i++) {        System.out.println(names.get(i));    }}

}

0 0
原创粉丝点击