List集合学习

Java中常用的List子类主要有:ArrayList、LinkedList、Vector。有序(存储和取出的元素一致),可重复的。

三者比较

    1:访问:ArrayList和Vector都实现了RandomAccess接口,提供了随机访问功能,查询O(1);LinkedList是链表,查询O(n);

    2:增删:ArrayList和Vector底层是数组,增删容易引起大量的内存操作,效率较慢;LinkedList是链表实现,增加和删除较快;

    3:线程安全性:Vector是线程安全的,大部分的方法都用了syncrhoized关键字修饰。如果是单线程下使用,可以用Arrayist,如果是多线程操作的list,则可以用Vector来保证线程安全。

    4:ArrayList每次扩容增加50%,Vector扩容增加一倍。

  一:ArrayList

   ArrayList实现了List接口,实现了一系列的add()/get()/clear()/remove()等接口中的方法。其底层其实是一个数组,通过对数组上一系列操作的封装来实现list的各种功能的。

   1:ArrayList 实际上是通过一个数组去保存数据的。当我们构造ArrayList时;若使用默认构造函数,则ArrayList的默认容量大小是10
      2:当ArrayList容量不足以容纳全部元素时,ArrayList扩容:新的容量=“(原始容量x3)/2 + 1”。创建新容量大小的数组并把原数组内容复制过去。

   3:底层数据结构是数组,查询快,增删慢。线程不安全,效率高。
底层源码:

  1 package java.util;
  2 
  3 public class ArrayList<E> extends AbstractList<E>
  4         implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  5 {
  6     // 序列版本号
  7     private static final long serialVersionUID = 8683452581122892189L;
  8 
  9     // 保存ArrayList中数据的数组
 10     private transient Object[] elementData;
 11 
 12     // ArrayList中实际数据的数量
 13     private int size;
 14 
 15     // ArrayList带容量大小的构造函数。
 16     public ArrayList(int initialCapacity) {
 17         super();
 18         if (initialCapacity < 0)
 19             throw new IllegalArgumentException("Illegal Capacity: "+
 20                                                initialCapacity);
 21         // 新建一个数组
 22         this.elementData = new Object[initialCapacity];
 23     }
 24 
 25     // ArrayList构造函数。默认容量是10。
 26     public ArrayList() {
 27         this(10);
 28     }
 29 
 30     // 创建一个包含collection的ArrayList
 31     public ArrayList(Collection<? extends E> c) {
 32         elementData = c.toArray();
 33         size = elementData.length;
 34         // c.toArray might (incorrectly) not return Object[] (see 6260652)
 35         if (elementData.getClass() != Object[].class)
 36             elementData = Arrays.copyOf(elementData, size, Object[].class);
 37     }
 38 
 39 
 40     // 将当前容量值设为 =实际元素个数
 41     public void trimToSize() {
 42         modCount++;
 43         int oldCapacity = elementData.length;
 44         if (size < oldCapacity) {
 45             elementData = Arrays.copyOf(elementData, size);
 46         }
 47     }
 48 
 49 
 50     // 确定ArrarList的容量。
 51     // 若ArrayList的容量不足以容纳当前的全部元素,设置 新的容量=“(原始容量x3)/2 + 1”
 52     public void ensureCapacity(int minCapacity) {
 53         // 将“修改统计数”+1
 54         modCount++;
 55         int oldCapacity = elementData.length;
 56         // 若当前容量不足以容纳当前的元素个数,设置 新的容量=“(原始容量x3)/2 + 1”
 57         if (minCapacity > oldCapacity) {
 58             Object oldData[] = elementData;
 59             int newCapacity = (oldCapacity * 3)/2 + 1;
 60             if (newCapacity < minCapacity)
 61                 newCapacity = minCapacity;
 62             elementData = Arrays.copyOf(elementData, newCapacity);
 63         }
 64     }
 65 
 66     // 添加元素e
 67     public boolean add(E e) {
 68         // 确定ArrayList的容量大小
 69         ensureCapacity(size + 1);  // Increments modCount!!
 70         // 添加e到ArrayList中
 71         elementData[size++] = e;
 72         return true;
 73     }
 74 
 75     // 返回ArrayList的实际大小
 76     public int size() {
 77         return size;
 78     }
 79 
 80     // 返回ArrayList是否包含Object(o)
 81     public boolean contains(Object o) {
 82         return indexOf(o) >= 0;
 83     }
 84 
 85     // 返回ArrayList是否为空
 86     public boolean isEmpty() {
 87         return size == 0;
 88     }
 89 
 90     // 正向查找,返回元素的索引值
 91     public int indexOf(Object o) {
 92         if (o == null) {
 93             for (int i = 0; i < size; i++)
 94             if (elementData[i]==null)
 95                 return i;
 96             } else {
 97                 for (int i = 0; i < size; i++)
 98                 if (o.equals(elementData[i]))
 99                     return i;
100             }
101             return -1;
102         }
103 
104         // 反向查找,返回元素的索引值
105         public int lastIndexOf(Object o) {
106         if (o == null) {
107             for (int i = size-1; i >= 0; i--)
108             if (elementData[i]==null)
109                 return i;
110         } else {
111             for (int i = size-1; i >= 0; i--)
112             if (o.equals(elementData[i]))
113                 return i;
114         }
115         return -1;
116     }
117 
118     // 反向查找(从数组末尾向开始查找),返回元素(o)的索引值
119     public int lastIndexOf(Object o) {
120         if (o == null) {
121             for (int i = size-1; i >= 0; i--)
122             if (elementData[i]==null)
123                 return i;
124         } else {
125             for (int i = size-1; i >= 0; i--)
126             if (o.equals(elementData[i]))
127                 return i;
128         }
129         return -1;
130     }
131  
132 
133     // 返回ArrayList的Object数组
134     public Object[] toArray() {
135         return Arrays.copyOf(elementData, size);
136     }
137 
138     // 返回ArrayList的模板数组。所谓模板数组,即可以将T设为任意的数据类型
139     public <T> T[] toArray(T[] a) {
140         // 若数组a的大小 < ArrayList的元素个数;
141         // 则新建一个T[]数组,数组大小是“ArrayList的元素个数”,并将“ArrayList”全部拷贝到新数组中
142         if (a.length < size)
143             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
144 
145         // 若数组a的大小 >= ArrayList的元素个数;
146         // 则将ArrayList的全部元素都拷贝到数组a中。
147         System.arraycopy(elementData, 0, a, 0, size);
148         if (a.length > size)
149             a[size] = null;
150         return a;
151     }
152 
153     // 获取index位置的元素值
154     public E get(int index) {
155         RangeCheck(index);
156 
157         return (E) elementData[index];
158     }
159 
160     // 设置index位置的值为element
161     public E set(int index, E element) {
162         RangeCheck(index);
163 
164         E oldValue = (E) elementData[index];
165         elementData[index] = element;
166         return oldValue;
167     }
168 
169     // 将e添加到ArrayList中
170     public boolean add(E e) {
171         ensureCapacity(size + 1);  // Increments modCount!!
172         elementData[size++] = e;
173         return true;
174     }
175 
176     // 将e添加到ArrayList的指定位置
177     public void add(int index, E element) {
178         if (index > size || index < 0)
179             throw new IndexOutOfBoundsException(
180             "Index: "+index+", Size: "+size);
181 
182         ensureCapacity(size+1);  // Increments modCount!!
183         System.arraycopy(elementData, index, elementData, index + 1,
184              size - index);
185         elementData[index] = element;
186         size++;
187     }
188 
189     // 删除ArrayList指定位置的元素
190     public E remove(int index) {
191         RangeCheck(index);
192 
193         modCount++;
194         E oldValue = (E) elementData[index];
195 
196         int numMoved = size - index - 1;
197         if (numMoved > 0)
198             System.arraycopy(elementData, index+1, elementData, index,
199                  numMoved);
200         elementData[--size] = null; // Let gc do its work
201 
202         return oldValue;
203     }
204 
205     // 删除ArrayList的指定元素
206     public boolean remove(Object o) {
207         if (o == null) {
208                 for (int index = 0; index < size; index++)
209             if (elementData[index] == null) {
210                 fastRemove(index);
211                 return true;
212             }
213         } else {
214             for (int index = 0; index < size; index++)
215             if (o.equals(elementData[index])) {
216                 fastRemove(index);
217                 return true;
218             }
219         }
220         return false;
221     }
222 
223 
224     // 快速删除第index个元素
225     private void fastRemove(int index) {
226         modCount++;
227         int numMoved = size - index - 1;
228         // 从"index+1"开始,用后面的元素替换前面的元素。
229         if (numMoved > 0)
230             System.arraycopy(elementData, index+1, elementData, index,
231                              numMoved);
232         // 将最后一个元素设为null
233         elementData[--size] = null; // Let gc do its work
234     }
235 
236     // 删除元素
237     public boolean remove(Object o) {
238         if (o == null) {
239             for (int index = 0; index < size; index++)
240             if (elementData[index] == null) {
241                 fastRemove(index);
242             return true;
243             }
244         } else {
245             // 便利ArrayList,找到“元素o”,则删除,并返回true。
246             for (int index = 0; index < size; index++)
247             if (o.equals(elementData[index])) {
248                 fastRemove(index);
249             return true;
250             }
251         }
252         return false;
253     }
254 
255     // 清空ArrayList,将全部的元素设为null
256     public void clear() {
257         modCount++;
258 
259         for (int i = 0; i < size; i++)
260             elementData[i] = null;
261 
262         size = 0;
263     }
264 
265     // 将集合c追加到ArrayList中
266     public boolean addAll(Collection<? extends E> c) {
267         Object[] a = c.toArray();
268         int numNew = a.length;
269         ensureCapacity(size + numNew);  // Increments modCount
270         System.arraycopy(a, 0, elementData, size, numNew);
271         size += numNew;
272         return numNew != 0;
273     }
274 
275     // 从index位置开始,将集合c添加到ArrayList
276     public boolean addAll(int index, Collection<? extends E> c) {
277         if (index > size || index < 0)
278             throw new IndexOutOfBoundsException(
279             "Index: " + index + ", Size: " + size);
280 
281         Object[] a = c.toArray();
282         int numNew = a.length;
283         ensureCapacity(size + numNew);  // Increments modCount
284 
285         int numMoved = size - index;
286         if (numMoved > 0)
287             System.arraycopy(elementData, index, elementData, index + numNew,
288                  numMoved);
289 
290         System.arraycopy(a, 0, elementData, index, numNew);
291         size += numNew;
292         return numNew != 0;
293     }
294 
295     // 删除fromIndex到toIndex之间的全部元素。
296     protected void removeRange(int fromIndex, int toIndex) {
297     modCount++;
298     int numMoved = size - toIndex;
299         System.arraycopy(elementData, toIndex, elementData, fromIndex,
300                          numMoved);
301 
302     // Let gc do its work
303     int newSize = size - (toIndex-fromIndex);
304     while (size != newSize)
305         elementData[--size] = null;
306     }
307 
308     private void RangeCheck(int index) {
309     if (index >= size)
310         throw new IndexOutOfBoundsException(
311         "Index: "+index+", Size: "+size);
312     }
313 
314 
315     // 克隆函数
316     public Object clone() {
317         try {
318             ArrayList<E> v = (ArrayList<E>) super.clone();
319             // 将当前ArrayList的全部元素拷贝到v中
320             v.elementData = Arrays.copyOf(elementData, size);
321             v.modCount = 0;
322             return v;
323         } catch (CloneNotSupportedException e) {
324             // this shouldn't happen, since we are Cloneable
325             throw new InternalError();
326         }
327     }
328 
329 
330     // java.io.Serializable的写入函数
331     // 将ArrayList的“容量,所有的元素值”都写入到输出流中
332     private void writeObject(java.io.ObjectOutputStream s)
333         throws java.io.IOException{
334     // Write out element count, and any hidden stuff
335     int expectedModCount = modCount;
336     s.defaultWriteObject();
337 
338         // 写入“数组的容量”
339         s.writeInt(elementData.length);
340 
341     // 写入“数组的每一个元素”
342     for (int i=0; i<size; i++)
343             s.writeObject(elementData[i]);
344 
345     if (modCount != expectedModCount) {
346             throw new ConcurrentModificationException();
347         }
348 
349     }
350 
351 
352     // java.io.Serializable的读取函数:根据写入方式读出
353     // 先将ArrayList的“容量”读出,然后将“所有的元素值”读出
354     private void readObject(java.io.ObjectInputStream s)
355         throws java.io.IOException, ClassNotFoundException {
356         // Read in size, and any hidden stuff
357         s.defaultReadObject();
358 
359         // 从输入流中读取ArrayList的“容量”
360         int arrayLength = s.readInt();
361         Object[] a = elementData = new Object[arrayLength];
362 
363         // 从输入流中将“所有的元素值”读出
364         for (int i=0; i<size; i++)
365             a[i] = s.readObject();
366     }
367 }
View Code

 Java中对ArrayList集合的常用操作

1.list中添加,获取,删除元素;

2.list中是否包含某个元素;

3.list中根据索引将元素数值改变(替换);

4.list中查看(判断)元素的索引;

5.根据元素索引位置进行的判断;

6.利用list中索引位置重新生成一个新的list(截取集合);

7.对比两个list中的所有元素;

8.判断list是否为空;

9.返回Iterator集合对象;

10.将集合转换为字符串;

11.将集合转换为数组;

12.集合类型转换;

备注:内容中代码具有关联性。

1.list中添加,获取,删除元素;
添加方法是:.add(e); 
获取方法是:.get(index);  
按照索引删除方法是:.remove(index)
按照元素内容删除方法是:.remove(Object o); List
<String> person=new ArrayList<>(); person.add("jackie"); //索引为0 //.add(e) person.add("peter"); //索引为1 person.add("annie"); //索引为2 person.add("martin"); //索引为3 person.add("marry"); //索引为4 person.remove(3); //.remove(index) person.remove("marry"); //.remove(Object o) String per=""; per=person.get(1); System.out.println(per); //.get(index) for (int i = 0; i < person.size(); i++) { System.out.println(person.get(i)); //.get(index) } 2.list中是否包含某个元素; 方法:.contains(Object o); 返回true或者false List<String> fruits=new ArrayList<>(); fruits.add("苹果"); fruits.add("香蕉"); fruits.add("桃子"); //for循环遍历list for (int i = 0; i < fruits.size(); i++) { System.out.println(fruits.get(i)); } String appleString="苹果"; //true or false System.out.println("fruits中是否包含苹果:"+fruits.contains(appleString)); if (fruits.contains(appleString)) { System.out.println("我喜欢吃苹果"); }else { System.out.println("我不开心"); } 3.list中根据索引将元素数值改变(替换); 注意 .set(index, element); 和 .add(index, element); 的不同; String a="白龙马", b="沙和尚", c="八戒", d="唐僧", e="悟空"; List<String> people=new ArrayList<>(); people.add(a); people.add(b); people.add(c); people.set(0, d); //.set(index, element); //将d唐僧放到list中索引为0的位置,替换a白龙马 people.add(1, e); //.add(index, element); //将e悟空放到list中索引为1的位置,原来位置的b沙和尚后移一位 //增强for循环遍历list for(String str:people){ System.out.println(str); } 4.list中查看(判断)元素的索引;   注意:indexOf()和lastIndexOf()的不同; List<String> names=new ArrayList<>(); names.add("刘备"); //索引为0 names.add("关羽"); //索引为1 names.add("张飞"); //索引为2 names.add("刘备"); //索引为3 names.add("张飞"); //索引为4 System.out.println(names.indexOf("刘备")); System.out.println(names.lastIndexOf("刘备")); System.out.println(names.indexOf("张飞")); System.out.println(names.lastIndexOf("张飞")); 5.根据元素索引位置进行的判断; if (names.indexOf("刘备")==0) { System.out.println("刘备在这里"); }else if (names.lastIndexOf("刘备")==3) { System.out.println("刘备在那里"); }else { System.out.println("刘备到底在哪里?"); } 6.利用list中索引位置重新生成一个新的list(截取集合); 方法: .subList(fromIndex,toIndex);.size();该方法得到list中的元素数的和 List<String> phone=new ArrayList<>(); phone.add("三星"); //索引为0 phone.add("苹果"); //索引为1 phone.add("锤子"); //索引为2 phone.add("华为"); //索引为3 phone.add("小米"); //索引为4 //原list进行遍历 for(String pho:phone){ System.out.println(pho); } //生成新list phone=phone.subList(1, 4); //.subList(fromIndex, toIndex) //利用索引1-4的对象重新生成一个list,但是不包含索引为4的元素,4-1=3 for (int i = 0; i < phone.size(); i++) { // phone.size() 该方法得到list中的元素数的和 System.out.println("新的list包含的元素是"+phone.get(i)); } 7.对比两个list中的所有元素;
//两个相等对象的equals方法一定为true, 但两个hashcode相等的对象不一定是相等的对象 //1.<BR>if (person.equals(fruits)) { System.out.println("两个list中的所有元素相同"); }else { System.out.println("两个list中的所有元素不一样"); } //2. if (person.hashCode()==fruits.hashCode()) { System.out.println("我们相同"); }else { System.out.println("我们不一样"); } 8.判断list是否为空; //空则返回true,非空则返回false if (person.isEmpty()) { System.out.println("空的"); }else { System.out.println("不是空的"); } 9.返回Iterator集合对象; System.out.println("返回Iterator集合对象:"+person.iterator()); 10.将集合转换为字符串; String liString=""; liString=person.toString(); System.out.println("将集合转换为字符串:"+liString); 11.将集合转换为数组; System.out.println("将集合转换为数组:"+person.toArray()); 12.集合类型转换; //1.默认类型 List<Object> listsStrings=new ArrayList<>();   for (int i = 0; i < person.size(); i++) { listsStrings.add(person.get(i)); } //2.指定类型 List<StringBuffer> lst=new ArrayList<>();   for(String string:person){   lst.add(StringBuffer(string)); }

二:LinkedList

    LinkedList通过另一种方式实现List接口,不仅如此,它还实现了 Queue、Deque接口,使得LinkedList可以作为栈、队列、双端队列来使用

 LinkedList底层是一个双向链表。其对于 List、Queue、Deque接口中的方法都是通过封装在链表上的操作来实现的。查询慢,增删快。线程不安全,效率高。

底层源码:

  1 package com.chy.collection.core;  
  2       
  3     import java.util.AbstractSequentialList;  
  4     import java.util.Collections;  
  5     import java.util.ConcurrentModificationException;  
  6     import java.util.Deque;  
  7     import java.util.Iterator;  
  8     import java.util.NoSuchElementException;  
  9     import java.util.Queue;  
 10     import java.util.Vector;  
 11       
 12     /** 
 13      * LinkedList实际上是通过双向链表去实现的、整个链表是通过Entry实体类来存储数据的 
 14      */  
 15       
 16     public class LinkedList<E>  
 17         extends AbstractSequentialList<E>  
 18         implements List<E>, Deque<E>, Cloneable, java.io.Serializable  
 19     {  
 20         //链表的表头、表头不包含任何数据、  
 21         //Entry是双向链表节点所对应的数据结构,它包括的属性有:当前节点所包含的值,上一个节点,下一个节点。  
 22         private transient Entry<E> header = new Entry<E>(null, null, null);  
 23           
 24         // LinkedList中元素个数  
 25         private transient int size = 0;  
 26       
 27         /** 
 28          * 构造一个空的LinkedList、只含有表头 
 29          */  
 30         public LinkedList() {  
 31             header.next = header.previous = header;  
 32         }  
 33       
 34         /** 
 35          * 创建一个包含c的LinkedList、先创建默认空、然后将c中所有元素添加到LinkedList中 
 36          */  
 37         public LinkedList(Collection<? extends E> c) {  
 38             this();  
 39             addAll(c);  
 40         }  
 41       
 42         /** 获取链表第一个元素、*/  
 43         public E getFirst() {  
 44             if (size==0)  
 45                 throw new NoSuchElementException();  
 46             //因其是双向链表、这里的header可视为顺序的第一个不含元素的表头、所以第一个是此header的下一个元素  
 47             return header.next.element;  
 48         }  
 49       
 50         /** 获取链表最后一个元素*/  
 51         public E getLast()  {  
 52         if (size==0)  
 53             throw new NoSuchElementException();  
 54             //因其是双向链表、这里的header可视为逆序的第一个不含元素的表头、所以最后一个是此header的上一个元素  
 55             return header.previous.element;  
 56         }  
 57       
 58         /** 删除LinkedList的第一个元素*/  
 59         public E removeFirst() {  
 60             return remove(header.next);  
 61         }  
 62       
 63         /** 删除LinkedList的最后一个元素*/  
 64         public E removeLast() {  
 65             return remove(header.previous);  
 66         }  
 67       
 68         /** 将元素e添加到LinkedList的起始位置*/  
 69         public void addFirst(E e) {  
 70             addBefore(e, header.next);  
 71         }  
 72       
 73         /** 将元素e添加到LinkedList的结束位置*/  
 74         public void addLast(E e) {  
 75             addBefore(e, header);  
 76         }  
 77       
 78         /** 判断是否包含Object o*/  
 79         public boolean contains(Object o) {  
 80             return indexOf(o) != -1;  
 81         }  
 82       
 83         /** 返回LinkedList的大小*/  
 84         public int size() {  
 85             return size;  
 86         }  
 87       
 88         /** 将元素(E)添加到LinkedList中、添加到末尾*/  
 89         public boolean add(E e) {  
 90             addBefore(e, header);  
 91             return true;  
 92         }  
 93       
 94         /** 从LinkedList中删除o、如果存在则删除第一查找到的o并返回true、若不存在则返回false*/  
 95         public boolean remove(Object o) {  
 96             if (o==null) {  
 97                 for (Entry<E> e = header.next; e != header; e = e.next) {  
 98                     if (e.element==null) {  
 99                         remove(e);  
100                         return true;  
101                     }  
102                 }  
103             } else {  
104                 for (Entry<E> e = header.next; e != header; e = e.next) {  
105                     if (o.equals(e.element)) {  
106                         remove(e);  
107                         return true;  
108                     }  
109                 }  
110             }  
111             return false;  
112         }  
113       
114         /** 将c中元素添加到双向链表LinkedList中、从尾部开始添加*/  
115         public boolean addAll(Collection<? extends E> c) {  
116             return addAll(size, c);  
117         }  
118       
119         /** 将c中元素添加到双向链表LinkedList中、所有元素添加到index与index+1表示的元素中间*/  
120         public boolean addAll(int index, Collection<? extends E> c) {  
121             if (index < 0 || index > size)  
122                 throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);  
123             //将c转换成数组、方便遍历元素和获取元素个数  
124             Object[] a = c.toArray();  
125             int numNew = a.length;  
126             if (numNew==0)  
127                 return false;  
128             modCount++;  
129       
130             //设置当前要插入节点的下一个节点  
131             Entry<E> successor = (index==size ? header : entry(index));  
132             //设置当前要插入节点的上一个节点  
133             Entry<E> predecessor = successor.previous;  
134             //将c中元素插入到LinkedList中  
135             for (int i=0; i<numNew; i++) {  
136                 Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);  
137                 predecessor.next = e;  
138                 predecessor = e;  
139             }  
140             successor.previous = predecessor;  
141             size += numNew;  
142             return true;  
143         }  
144       
145         /** 删除LinkedList中所有元素*/  
146         public void clear() {  
147             Entry<E> e = header.next;  
148             while (e != header) {  
149                 Entry<E> next = e.next;  
150                 e.next = e.previous = null;  
151                 e.element = null;  
152                 e = next;  
153             }  
154             header.next = header.previous = header;  
155             size = 0;  
156             modCount++;  
157         }  
158       
159       
160         // Positional Access Operations  
161       
162         /** 获取index处的元素*/  
163         public E get(int index) {  
164             return entry(index).element;  
165         }  
166       
167         /** 设置index处的元素、并将old元素返回*/  
168         public E set(int index, E element) {  
169             Entry<E> e = entry(index);  
170             E oldVal = e.element;  
171             e.element = element;  
172             return oldVal;  
173         }  
174       
175         /** 在index前添加节点,且节点的值为element*/  
176         public void add(int index, E element) {  
177             addBefore(element, (index==size ? header : entry(index)));  
178         }  
179       
180         /** 删除index位置的节点*/  
181         public E remove(int index) {  
182             return remove(entry(index));  
183         }  
184       
185         /**  获取双向链表LinkedList中指定位置的节点、是LinkedList实现List中通过index操作元素的关键*/  
186         private Entry<E> entry(int index) {  
187             if (index < 0 || index >= size)  
188                 throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);  
189             Entry<E> e = header;  
190             if (index < (size >> 1)) {  
191                 for (int i = 0; i <= index; i++)  
192                     e = e.next;  
193             } else {  
194                 for (int i = size; i > index; i--)  
195                     e = e.previous;  
196             }  
197             return e;  
198         }  
199       
200       
201         // Search Operations  
202       
203         /** 查询o所在LinkedList中的位置的索引、从前向后、不存在返回-1*/  
204         public int indexOf(Object o) {  
205             int index = 0;  
206             if (o==null) {  
207                 for (Entry e = header.next; e != header; e = e.next) {  
208                     if (e.element==null)  
209                         return index;  
210                     index++;  
211                 }  
212             } else {  
213                 for (Entry e = header.next; e != header; e = e.next) {  
214                     if (o.equals(e.element))  
215                         return index;  
216                     index++;  
217                 }  
218             }  
219             return -1;  
220         }  
221       
222         /** 查询o所在LinkedList中的位置的索引、从后向前、不存在返回-1*/  
223         public int lastIndexOf(Object o) {  
224             int index = size;  
225             if (o==null) {  
226                 for (Entry e = header.previous; e != header; e = e.previous) {  
227                     index--;  
228                     if (e.element==null)  
229                         return index;  
230                 }  
231             } else {  
232                 for (Entry e = header.previous; e != header; e = e.previous) {  
233                     index--;  
234                     if (o.equals(e.element))  
235                         return index;  
236                 }  
237             }  
238             return -1;  
239         }  
240       
241         // Queue operations.  
242       
243         /** 返回第一个节点、若size为0则返回null*/  
244         public E peek() {  
245             if (size==0)  
246                 return null;  
247             return getFirst();  
248         }  
249       
250         /** 返回第一个节点、若size为0则抛异常NoSuchElementException*/  
251         public E element() {  
252             return getFirst();  
253         }  
254       
255         /** 删除并返回第一个节点 、若LinkedList的大小为0,则返回null*/  
256         public E poll() {  
257             if (size==0)  
258                 return null;  
259             return removeFirst();  
260         }  
261       
262         /** 删除第一个元素、若LinkedList的大小为0,则抛异常*/  
263         public E remove() {  
264             return removeFirst();  
265         }  
266       
267         /** 将e添加双向链表末尾*/  
268         public boolean offer(E e) {  
269             return add(e);  
270         }  
271       
272         // Deque operations  
273         /** 将e添加双向链表开头*/  
274         public boolean offerFirst(E e) {  
275             addFirst(e);  
276             return true;  
277         }  
278       
279         /** 将e添加双向链表末尾*/  
280         public boolean offerLast(E e) {  
281             addLast(e);  
282             return true;  
283         }  
284       
285         /**返回第一个节点、若LinkedList的大小为0,则返回null*/  
286         public E peekFirst() {  
287             if (size==0)  
288                 return null;  
289             return getFirst();  
290         }  
291       
292         /**返回最后一个节点、 若LinkedList的大小为0,则返回null*/  
293         public E peekLast() {  
294             if (size==0)  
295                 return null;  
296             return getLast();  
297         }  
298       
299         /** 删除并返回第一个、若LinkedList的大小为0,则返回null*/  
300         public E pollFirst() {  
301             if (size==0)  
302                 return null;  
303             return removeFirst();  
304         }  
305       
306         /** 删除并返回最后一个、若LinkedList的大小为0,则返回null*/  
307         public E pollLast() {  
308             if (size==0)  
309                 return null;  
310             return removeLast();  
311         }  
312       
313         /** 将e插入到双向链表开头*/  
314         public void push(E e) {  
315             addFirst(e);  
316         }  
317       
318         /** 删除并返回第一个节点*/  
319         public E pop() {  
320             return removeFirst();  
321         }  
322       
323         /** 从LinkedList中删除o、如果存在则删除第一查找到的o并返回true、若不存在则返回false*/  
324         public boolean removeFirstOccurrence(Object o) {  
325             return remove(o);  
326         }  
327       
328         /** 从LinkedList末尾向前查找,删除第一个值为元素(o)的节点*/  
329         public boolean removeLastOccurrence(Object o) {  
330             if (o==null) {  
331                 for (Entry<E> e = header.previous; e != header; e = e.previous) {  
332                     if (e.element==null) {  
333                         remove(e);  
334                         return true;  
335                     }  
336                 }  
337             } else {  
338                 for (Entry<E> e = header.previous; e != header; e = e.previous) {  
339                     if (o.equals(e.element)) {  
340                         remove(e);  
341                         return true;  
342                     }  
343                 }  
344             }  
345             return false;  
346         }  
347       
348         /** 返回“index到末尾的全部节点”对应的ListIterator对象(List迭代器)*/  
349         public ListIterator<E> listIterator(int index) {  
350             return new ListItr(index);  
351         }  
352       
353         private class ListItr implements ListIterator<E> {  
354             // 上一次返回的节点  
355             private Entry<E> lastReturned = header;  
356             // 下一个节点  
357             private Entry<E> next;  
358             // 下一个节点对应的索引值  
359             private int nextIndex;  
360             // 期望的改变计数。用来实现fail-fast机制。  
361             private int expectedModCount = modCount;  
362               
363             //构造函数、 从index位置开始进行迭代  
364             ListItr(int index) {  
365                 if (index < 0 || index > size)  
366                     throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);  
367                 /* 
368                  *  若 “index 小于 ‘双向链表长度的一半’”,则从第一个元素开始往后查找; 
369                  *  否则,从最后一个元素往前查找。 
370                  */  
371                 if (index < (size >> 1)) {  
372                     next = header.next;  
373                     for (nextIndex=0; nextIndex<index; nextIndex++)  
374                         next = next.next;  
375                 } else {  
376                     next = header;  
377                     for (nextIndex=size; nextIndex>index; nextIndex--)  
378                         next = next.previous;  
379                 }  
380             }  
381             // 是否存在下一个元素  
382             public boolean hasNext() {  
383                 return nextIndex != size;  
384             }  
385             // 获取下一个元素  
386             public E next() {  
387                 checkForComodification();  
388                 if (nextIndex == size)  
389                 throw new NoSuchElementException();  
390           
391                 lastReturned = next;  
392                 next = next.next;  
393                 nextIndex++;  
394                 return lastReturned.element;  
395             }  
396       
397             // 是否存在上一个元素  
398             public boolean hasPrevious() {  
399                 return nextIndex != 0;  
400             }  
401             // 获取上一个元素  
402             public E previous() {  
403                 if (nextIndex == 0)  
404                 throw new NoSuchElementException();  
405           
406                 lastReturned = next = next.previous;  
407                 nextIndex--;  
408                 checkForComodification();  
409                 return lastReturned.element;  
410             }  
411       
412             // 获取下一个元素的索引  
413             public int nextIndex() {  
414                 return nextIndex;  
415             }  
416           
417             // 获取上一个元素的索引  
418             public int previousIndex() {  
419                 return nextIndex-1;  
420             }  
421             // 删除双向链表中的当前节点  
422             public void remove() {  
423                     checkForComodification();  
424                     Entry<E> lastNext = lastReturned.next;  
425                     try {  
426                         LinkedList.this.remove(lastReturned);  
427                     } catch (NoSuchElementException e) {  
428                         throw new IllegalStateException();  
429                     }  
430                 if (next==lastReturned)  
431                         next = lastNext;  
432                     else  
433                 nextIndex--;  
434                 lastReturned = header;  
435                 expectedModCount++;  
436             }  
437             // 设置当前节点为e  
438             public void set(E e) {  
439                 if (lastReturned == header)  
440                 throw new IllegalStateException();  
441                 checkForComodification();  
442                 lastReturned.element = e;  
443             }  
444             // 将e添加到当前节点的前面  
445             public void add(E e) {  
446                 checkForComodification();  
447                 lastReturned = header;  
448                 addBefore(e, next);  
449                 nextIndex++;  
450                 expectedModCount++;  
451             }  
452             // 判断 “modCount和expectedModCount是否相等”,以此来实现fail-fast机制。  
453             final void checkForComodification() {  
454                 if (modCount != expectedModCount)  
455                     throw new ConcurrentModificationException();  
456             }  
457         }  
458       
459         /** 
460          * 内部静态类、是双向链表的节点所对应的数据结构、 
461          * 此数据结构包含三部分:上一节点、下一节点、当前节点值 
462          */  
463         private static class Entry<E> {  
464             //当前节点值  
465             E element;  
466             //下一节点  
467             Entry<E> next;  
468             //上一节点  
469             Entry<E> previous;  
470       
471             /** 
472              * 链表节点构造函数 
473              * @param element   节点值 
474              * @param next      下一节点 
475              * @param previous  上一节点 
476              */  
477             Entry(E element, Entry<E> next, Entry<E> previous) {  
478                 this.element = element;  
479                 this.next = next;  
480                 this.previous = previous;  
481             }  
482         }  
483       
484         //新建节点、节点值是e、将新建的节点添加到entry之前  
485         private Entry<E> addBefore(E e, Entry<E> entry) {  
486             //觉得难理解的可以先花个几分钟看一下链式结构资料、最好是图片形式的  
487             //新建节点实体  
488             Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);  
489             //将参照节点原来的上一个节点(即插在谁前面的)的下一个节点设置成newEntry  
490             newEntry.previous.next = newEntry;  
491             //将参照节点(即插在谁前面的)的前一个节点设置成newEntry  
492             newEntry.next.previous = newEntry;  
493             size++;  
494             modCount++;  
495             return newEntry;  
496         }  
497       
498           
499         //将节点从链表中删除、返回被删除的节点的内容  
500         private E remove(Entry<E> e) {  
501             //如果是表头、抛异常  
502             if (e == header)  
503                 throw new NoSuchElementException();  
504       
505             E result = e.element;  
506             //下面实际上就是、将e拿掉、然后将e的上下两个节点连接起来  
507             e.previous.next = e.next;  
508             e.next.previous = e.previous;  
509             e.next = e.previous = null;  
510             e.element = null;  
511             size--;  
512             modCount++;  
513             return result;  
514         }  
515       
516         /** 
517          * 反向迭代器 
518          * @since 1.6 
519          */  
520         public Iterator<E> descendingIterator() {  
521             return new DescendingIterator();  
522         }  
523       
524         /** 反向迭代器实现类 */  
525         private class DescendingIterator implements Iterator {  
526             final ListItr itr = new ListItr(size());  
527             public boolean hasNext() {  
528                 return itr.hasPrevious();  
529             }  
530             public E next() {  
531                 return itr.previous();  
532             }  
533             public void remove() {  
534                 itr.remove();  
535             }  
536         }  
537       
538         /** 返回LinkedList的克隆对象*/  
539         public Object clone() {  
540             LinkedList<E> clone = null;  
541             try {  
542                 clone = (LinkedList<E>) super.clone();  
543             } catch (CloneNotSupportedException e) {  
544                 throw new InternalError();  
545             }  
546       
547             // Put clone into "virgin" state  
548             clone.header = new Entry<E>(null, null, null);  
549             clone.header.next = clone.header.previous = clone.header;  
550             clone.size = 0;  
551             clone.modCount = 0;  
552       
553             // Initialize clone with our elements  
554             for (Entry<E> e = header.next; e != header; e = e.next)  
555                 clone.add(e.element);  
556       
557             return clone;  
558         }  
559       
560         /** 将LinkedList中的所有元素转换成Object[]中*/  
561         public Object[] toArray() {  
562             Object[] result = new Object[size];  
563             int i = 0;  
564             for (Entry<E> e = header.next; e != header; e = e.next)  
565                 result[i++] = e.element;  
566             return result;  
567         }  
568       
569         /** 将LinkedList中的所有元素转换成Object[]中、并且完成类型转换*/  
570         public <T> T[] toArray(T[] a) {  
571             if (a.length < size)  
572                 a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);  
573             int i = 0;  
574             Object[] result = a;  
575             for (Entry<E> e = header.next; e != header; e = e.next)  
576                 result[i++] = e.element;  
577       
578             if (a.length > size)  
579                 a[size] = null;  
580       
581             return a;  
582         }  
583       
584         private static final long serialVersionUID = 876323262645176354L;  
585       
586         /** 将LinkedList的“容量,所有的元素值”都写入到输出流中 
587          *  1、将LinkedList的容量写入进去 
588          *  2、将LinkedList中的所有元素写入进去  
589          */  
590         private void writeObject(java.io.ObjectOutputStream s)  
591             throws java.io.IOException {  
592             // Write out any hidden serialization magic  
593             s.defaultWriteObject();  
594       
595             // Write out size  
596             s.writeInt(size);  
597       
598             // Write out all elements in the proper order.  
599             for (Entry e = header.next; e != header; e = e.next)  
600                 s.writeObject(e.element);  
601         }  
602       
603         /**  
604          *  将写入的LinkedList读取出来 
605          *  1、读取写入的LinkedList的容量 
606          *  2、读取写入的元素  
607          */  
608         private void readObject(java.io.ObjectInputStream s)  
609             throws java.io.IOException, ClassNotFoundException {  
610             // Read in any hidden serialization magic  
611             s.defaultReadObject();  
612       
613             // Read in size  
614             int size = s.readInt();  
615       
616             // Initialize header  
617             header = new Entry<E>(null, null, null);  
618             header.next = header.previous = header;  
619       
620             // Read in all elements in the proper order.  
621             for (int i=0; i<size; i++)  
622                 addBefore((E)s.readObject(), header);  
623         }  
624     }
View Code

三:Vector

   Vector也是在底层通过一个数组来保存数据,通过底层数组的一系列操作来实现List接口。同ArrayList一样,Vector底层数组容量不足时会扩容,然后把原有内容复制过去。底层数据结构是数组,查询快,增删慢。线程不安全,效率高。线程安全,效率低。  

底层源码:

  1 package java.util;
  2 public class Vector<E>
  3     extends AbstractList<E>
  4     implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  5 {
  6 
  7     // 保存Vector中数据的数组
  8     protected Object[] elementData;
  9     // 实际数据的数量
 10     protected int elementCount;
 11     // 容量增长系数
 12     protected int capacityIncrement;
 13     // Vector的序列版本号
 14     private static final long serialVersionUID = -2767605614048989439L;
 15     // Vector构造函数。默认容量是10。
 16     public Vector() {
 17         this(10);
 18     }
 19     // 指定Vector容量大小的构造函数
 20     public Vector(int initialCapacity) {
 21         this(initialCapacity, 0);
 22     }
 23     // 指定Vector"容量大小"和"增长系数"的构造函数
 24     public Vector(int initialCapacity, int capacityIncrement) {
 25         super();
 26         if (initialCapacity < 0)
 27             throw new IllegalArgumentException("Illegal Capacity: "+
 28                                                initialCapacity);
 29         // 新建一个数组,数组容量是initialCapacity
 30         this.elementData = new Object[initialCapacity];
 31         // 设置容量增长系数
 32         this.capacityIncrement = capacityIncrement;
 33     }
 34     // 指定集合的Vector构造函数。
 35     public Vector(Collection<? extends E> c) {
 36         // 获取“集合(c)”的数组,并将其赋值给elementData
 37         elementData = c.toArray();
 38         // 设置数组长度
 39         elementCount = elementData.length;
 40         // c.toArray might (incorrectly) not return Object[] (see 6260652)
 41         if (elementData.getClass() != Object[].class)
 42             elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
 43     }
 44     // 将数组Vector的全部元素都拷贝到数组anArray中
 45     public synchronized void copyInto(Object[] anArray) {
 46         System.arraycopy(elementData, 0, anArray, 0, elementCount);
 47     }
 48     // 将当前容量值设为 =实际元素个数
 49     public synchronized void trimToSize() {
 50         modCount++;
 51         int oldCapacity = elementData.length;
 52         if (elementCount < oldCapacity) {
 53             elementData = Arrays.copyOf(elementData, elementCount);
 54         }
 55     }
 56     // 确认“Vector容量”的帮助函数
 57     private void ensureCapacityHelper(int minCapacity) {
 58         int oldCapacity = elementData.length;
 59         // 当Vector的容量不足以容纳当前的全部元素,增加容量大小。
 60         // 若 容量增量系数>0(即capacityIncrement>0),则将容量增大当capacityIncrement
 61         // 否则,将容量增大一倍。
 62         if (minCapacity > oldCapacity) {
 63             Object[] oldData = elementData;
 64             int newCapacity = (capacityIncrement > 0) ?
 65                 (oldCapacity + capacityIncrement) : (oldCapacity * 2);
 66             if (newCapacity < minCapacity) {
 67                 newCapacity = minCapacity;
 68             }
 69             elementData = Arrays.copyOf(elementData, newCapacity);
 70         }
 71     }
 72     // 确定Vector的容量。
 73     public synchronized void ensureCapacity(int minCapacity) {
 74         // 将Vector的改变统计数+1
 75         modCount++;
 76         ensureCapacityHelper(minCapacity);
 77     }
 78     // 设置容量值为 newSize
 79     public synchronized void setSize(int newSize) {
 80         modCount++;
 81         if (newSize > elementCount) {
 82             // 若 "newSize 大于 Vector容量",则调整Vector的大小。
 83             ensureCapacityHelper(newSize);
 84         } else {
 85             // 若 "newSize 小于/等于 Vector容量",则将newSize位置开始的元素都设置为null
 86             for (int i = newSize ; i < elementCount ; i++) {
 87                 elementData[i] = null;
 88             }
 89         }
 90         elementCount = newSize;
 91     }
 92     // 返回“Vector的总的容量”
 93     public synchronized int capacity() {
 94         return elementData.length;
 95     }
 96     // 返回“Vector的实际大小”,即Vector中元素个数
 97     public synchronized int size() {
 98         return elementCount;
 99     }
100     // 判断Vector是否为空
101     public synchronized boolean isEmpty() {
102         return elementCount == 0;
103     }
104     // 返回“Vector中全部元素对应的Enumeration”
105     public Enumeration<E> elements() {
106         // 通过匿名类实现Enumeration
107         return new Enumeration<E>() {
108             int count = 0;
109             // 是否存在下一个元素
110             public boolean hasMoreElements() {
111                 return count < elementCount;
112             }
113             // 获取下一个元素
114             public E nextElement() {
115                 synchronized (Vector.this) {
116                     if (count < elementCount) {
117                         return (E)elementData[count++];
118                     }
119                 }
120                 throw new NoSuchElementException("Vector Enumeration");
121             }
122         };
123     }
124     // 返回Vector中是否包含对象(o)
125     public boolean contains(Object o) {
126         return indexOf(o, 0) >= 0;
127     }
128 
129     // 从index位置开始向后查找元素(o)。
130     // 若找到,则返回元素的索引值;否则,返回-1
131     public synchronized int indexOf(Object o, int index) {
132         if (o == null) {
133             // 若查找元素为null,则正向找出null元素,并返回它对应的序号
134             for (int i = index ; i < elementCount ; i++)
135             if (elementData[i]==null)
136                 return i;
137         } else {
138             // 若查找元素不为null,则正向找出该元素,并返回它对应的序号
139             for (int i = index ; i < elementCount ; i++)
140             if (o.equals(elementData[i]))
141                 return i;
142         }
143         return -1;
144     }
145     // 查找并返回元素(o)在Vector中的索引值
146     public int indexOf(Object o) {
147         return indexOf(o, 0);
148     }
149     // 从后向前查找元素(o)。并返回元素的索引
150     public synchronized int lastIndexOf(Object o) {
151         return lastIndexOf(o, elementCount-1);
152     }
153     // 从后向前查找元素(o)。开始位置是从前向后的第index个数;
154     // 若找到,则返回元素的“索引值”;否则,返回-1。
155     public synchronized int lastIndexOf(Object o, int index) {
156         if (index >= elementCount)
157             throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
158         if (o == null) {
159             // 若查找元素为null,则反向找出null元素,并返回它对应的序号
160             for (int i = index; i >= 0; i--)
161             if (elementData[i]==null)
162                 return i;
163         } else {
164             // 若查找元素不为null,则反向找出该元素,并返回它对应的序号
165             for (int i = index; i >= 0; i--)
166             if (o.equals(elementData[i]))
167                 return i;
168         }
169         return -1;
170     }
171     // 返回Vector中index位置的元素。
172     // 若index月结,则抛出异常
173     public synchronized E elementAt(int index) {
174         if (index >= elementCount) {
175             throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
176         }
177         return (E)elementData[index];
178     }
179     // 获取Vector中的第一个元素。
180     // 若失败,则抛出异常!
181     public synchronized E firstElement() {
182         if (elementCount == 0) {
183             throw new NoSuchElementException();
184         }
185         return (E)elementData[0];
186     }
187     // 获取Vector中的最后一个元素。
188     // 若失败,则抛出异常!
189     public synchronized E lastElement() {
190         if (elementCount == 0) {
191             throw new NoSuchElementException();
192         }
193         return (E)elementData[elementCount - 1];
194     }
195     // 设置index位置的元素值为obj
196     public synchronized void setElementAt(E obj, int index) {
197         if (index >= elementCount) {
198             throw new ArrayIndexOutOfBoundsException(index + " >= " +
199                                  elementCount);
200         }
201         elementData[index] = obj;
202     }
203     // 删除index位置的元素
204     public synchronized void removeElementAt(int index) {
205         modCount++;
206         if (index >= elementCount) {
207             throw new ArrayIndexOutOfBoundsException(index + " >= " +
208                                  elementCount);
209         } else if (index < 0) {
210             throw new ArrayIndexOutOfBoundsException(index);
211         }
212         int j = elementCount - index - 1;
213         if (j > 0) {
214             System.arraycopy(elementData, index + 1, elementData, index, j);
215         }
216         elementCount--;
217         elementData[elementCount] = null; /* to let gc do its work */
218     }
219     // 在index位置处插入元素(obj)
220     public synchronized void insertElementAt(E obj, int index) {
221         modCount++;
222         if (index > elementCount) {
223             throw new ArrayIndexOutOfBoundsException(index
224                                  + " > " + elementCount);
225         }
226         ensureCapacityHelper(elementCount + 1);
227         System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
228         elementData[index] = obj;
229         elementCount++;
230     }
231     // 将“元素obj”添加到Vector末尾
232     public synchronized void addElement(E obj) {
233         modCount++;
234         ensureCapacityHelper(elementCount + 1);
235         elementData[elementCount++] = obj;
236     }
237     // 在Vector中查找并删除元素obj。
238     // 成功的话,返回true;否则,返回false。
239     public synchronized boolean removeElement(Object obj) {
240         modCount++;
241         int i = indexOf(obj);
242         if (i >= 0) {
243             removeElementAt(i);
244             return true;
245         }
246         return false;
247     }
248     // 删除Vector中的全部元素
249     public synchronized void removeAllElements() {
250         modCount++;
251         // 将Vector中的全部元素设为null
252         for (int i = 0; i < elementCount; i++)
253             elementData[i] = null;
254         elementCount = 0;
255     }
256     // 克隆函数
257     public synchronized Object clone() {
258         try {
259             Vector<E> v = (Vector<E>) super.clone();
260             // 将当前Vector的全部元素拷贝到v中
261             v.elementData = Arrays.copyOf(elementData, elementCount);
262             v.modCount = 0;
263             return v;
264         } catch (CloneNotSupportedException e) {
265             // this shouldn't happen, since we are Cloneable
266             throw new InternalError();
267         }
268     }
269     // 返回Object数组
270     public synchronized Object[] toArray() {
271         return Arrays.copyOf(elementData, elementCount);
272     }
273     // 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型
274     public synchronized <T> T[] toArray(T[] a) {
275         // 若数组a的大小 < Vector的元素个数;
276         // 则新建一个T[]数组,数组大小是“Vector的元素个数”,并将“Vector”全部拷贝到新数组中
277         if (a.length < elementCount)
278             return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
279         // 若数组a的大小 >= Vector的元素个数;
280         // 则将Vector的全部元素都拷贝到数组a中。
281     System.arraycopy(elementData, 0, a, 0, elementCount);
282         if (a.length > elementCount)
283             a[elementCount] = null;
284         return a;
285     }
286     // 获取index位置的元素
287     public synchronized E get(int index) {
288         if (index >= elementCount)
289             throw new ArrayIndexOutOfBoundsException(index);
290         return (E)elementData[index];
291     }
292     // 设置index位置的值为element。并返回index位置的原始值
293     public synchronized E set(int index, E element) {
294         if (index >= elementCount)
295             throw new ArrayIndexOutOfBoundsException(index);
296         Object oldValue = elementData[index];
297         elementData[index] = element;
298         return (E)oldValue;
299     }
300     // 将“元素e”添加到Vector最后。
301     public synchronized boolean add(E e) {
302         modCount++;
303         ensureCapacityHelper(elementCount + 1);
304         elementData[elementCount++] = e;
305         return true;
306     }
307     // 删除Vector中的元素o
308     public boolean remove(Object o) {
309         return removeElement(o);
310     }
311     // 在index位置添加元素element
312     public void add(int index, E element) {
313         insertElementAt(element, index);
314     }
315     // 删除index位置的元素,并返回index位置的原始值
316     public synchronized E remove(int index) {
317         modCount++;
318         if (index >= elementCount)
319             throw new ArrayIndexOutOfBoundsException(index);
320         Object oldValue = elementData[index];
321         int numMoved = elementCount - index - 1;
322         if (numMoved > 0)
323             System.arraycopy(elementData, index+1, elementData, index,
324                      numMoved);
325         elementData[--elementCount] = null; // Let gc do its work
326         return (E)oldValue;
327     }
328     // 清空Vector
329     public void clear() {
330         removeAllElements();
331     }
332     // 返回Vector是否包含集合c
333     public synchronized boolean containsAll(Collection<?> c) {
334         return super.containsAll(c);
335     }
336     // 将集合c添加到Vector中
337     public synchronized boolean addAll(Collection<? extends E> c) {
338         modCount++;
339         Object[] a = c.toArray();
340         int numNew = a.length;
341         ensureCapacityHelper(elementCount + numNew);
342         // 将集合c的全部元素拷贝到数组elementData中
343         System.arraycopy(a, 0, elementData, elementCount, numNew);
344         elementCount += numNew;
345         return numNew != 0;
346     }
347     // 删除集合c的全部元素
348     public synchronized boolean removeAll(Collection<?> c) {
349         return super.removeAll(c);
350     }
351     // 删除“非集合c中的元素”
352     public synchronized boolean retainAll(Collection<?> c)  {
353         return super.retainAll(c);
354     }
355     // 从index位置开始,将集合c添加到Vector中
356     public synchronized boolean addAll(int index, Collection<? extends E> c) {
357         modCount++;
358         if (index < 0 || index > elementCount)
359             throw new ArrayIndexOutOfBoundsException(index);
360         Object[] a = c.toArray();
361         int numNew = a.length;
362         ensureCapacityHelper(elementCount + numNew);
363         int numMoved = elementCount - index;
364         if (numMoved > 0)
365         System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
366         System.arraycopy(a, 0, elementData, index, numNew);
367         elementCount += numNew;
368         return numNew != 0;
369     }
370     // 返回两个对象是否相等
371     public synchronized boolean equals(Object o) {
372         return super.equals(o);
373     }
374     // 计算哈希值
375     public synchronized int hashCode() {
376         return super.hashCode();
377     }
378     // 调用父类的toString()
379     public synchronized String toString() {
380         return super.toString();
381     }
382     // 获取Vector中fromIndex(包括)到toIndex(不包括)的子集
383     public synchronized List<E> subList(int fromIndex, int toIndex) {
384         return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);
385     }
386     // 删除Vector中fromIndex到toIndex的元素
387     protected synchronized void removeRange(int fromIndex, int toIndex) {
388         modCount++;
389         int numMoved = elementCount - toIndex;
390         System.arraycopy(elementData, toIndex, elementData, fromIndex,
391                          numMoved);
392         // Let gc do its work
393         int newElementCount = elementCount - (toIndex-fromIndex);
394         while (elementCount != newElementCount)
395             elementData[--elementCount] = null;
396     }
397     // java.io.Serializable的写入函数
398     private synchronized void writeObject(java.io.ObjectOutputStream s)
399         throws java.io.IOException {
400         s.defaultWriteObject();
401     }
402 }
View Code

猜你喜欢

转载自www.cnblogs.com/huangdabing/p/9249237.html