@xmruibi
2015-02-14T18:18:40.000000Z
字数 8186
阅读 1650
Data_Structure
public interface List<E> extends Collection<E> {/****** Extends Collection Interface ******/int size();boolean isEmpty();boolean contains(Object o);Iterator<E> iterator();Object[] toArray();<T> T[] toArray(T[] a);boolean add(E e);boolean remove(Object o);boolean containsAll(Collection<?> c);boolean addAll(Collection<? extends E> c);boolean addAll(int index, Collection<? extends E> c);boolean removeAll(Collection<?> c);boolean retainAll(Collection<?> c);void clear();boolean equals(Object o);int hashCode();/***** Implementations of List Interface *****/E get(int index);// get the index-th elementE set(int index, E element);//set index-th element as new onevoid add(int index, E element);//insert the element before the original index-th elementE remove(int index);// remove the index-th elementint indexOf(Object o);// get index from the headint lastIndexOf(Object o);// get the index from the lastListIterator<E> listIterator();//返回系列表迭代器ListIterator<E> listIterator(int index);//从第index开始的系列表迭代器,该迭代器介绍如下List<E> subList(int fromIndex, int toIndex);//a kind of replica for current list, it isn't a new instance, but reference to original list elements. So any operation on sublist can effect the original element.}
AbstractList: is to achieve main implementation of List interface, reduce the workload of "Random Access" data collection (ArrayList).
AbstractSequentialList: for "Consecutive Access" data collection (LinkedList)
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>{protected AbstractList() {//提供一个空的构造函数}/**** No implemented ****/public boolean add(E e) {//在尾部添加元素eadd(size(), e);//在尾部执行添加操作return true;}abstract public E get(int index);public E set(int index, E element) {throw new UnsupportedOperationException();}public void add(int index, E element) {throw new UnsupportedOperationException();}public E remove(int index) {throw new UnsupportedOperationException();}/*********** Notice the following implemention are relied on list iterator ***********/// Get the index of given object from the collection beginningpublic int indexOf(Object o) {ListIterator<E> it = listIterator();if (o==null) {while (it.hasNext())if (it.next()==null)return it.previousIndex();} else {while (it.hasNext())if (o.equals(it.next()))return it.previousIndex();}return -1;}// Get the index of given object from the collection endpublic int lastIndexOf(Object o) {ListIterator<E> it = listIterator(size());if (o==null) {while (it.hasPrevious())if (it.previous()==null)return it.nextIndex();} else {while (it.hasPrevious())if (o.equals(it.previous()))return it.nextIndex();}return -1;}/*******************/public void clear() {removeRange(0, size());}public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);boolean modified = false;for (E e : c) {add(index++, e);modified = true;}return modified;}/************** Forward-Direction ***************/public Iterator<E> iterator() {//return new Itr();}private class Itr implements Iterator<E> {int cursor = 0;// current positionint lastRet = -1;//last position of cursorint expectedModCount = modCount;//for thread safepublic boolean hasNext() {return cursor != size();//just check the cursor is not in the last}// One directionpublic E next() {checkForComodification();// for concurrency to check if the list changed during iterationtry {int i = cursor;// current positionE next = get(i);// get the element by positionlastRet = i;// record last positioncursor = i + 1;// new positioin (next position)return next;} catch (IndexOutOfBoundsException e) {checkForComodification();//why check again???throw new NoSuchElementException();}}//remove method inside the iteratorpublic void remove() {if (lastRet < 0)//only can remove the visited elementthrow new IllegalStateException();checkForComodification();try {AbstractList.this.remove(lastRet);//parent interface remove implmentationif (lastRet < cursor)cursor--; // back the current positionlastRet = -1;//back the lastRetexpectedModCount = modCount;//modified expectedModCount} catch (IndexOutOfBoundsException e) {throw new ConcurrentModificationException();}}/****************** For concurrency check *******************/final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}}/************** Bidirectional ***************/public ListIterator<E> listIterator() {// default from 0 (beginning)return listIterator(0);}public ListIterator<E> listIterator(final int index) {rangeCheckForAdd(index);//inside the listreturn new ListItr(index);}//Bidirectional iterator extends Forward-Iteratorprivate class ListItr extends Itr implements ListIterator<E> {ListItr(int index) {// initial by given indexcursor = index;// set current cursor as given index}public boolean hasPrevious() {return cursor != 0;}public E previous() {checkForComodification();// for concurrencytry {int i = cursor - 1;E previous = get(i);lastRet = cursor = i;//lastRet always for the last visited positionreturn previous;} catch (IndexOutOfBoundsException e) {checkForComodification();throw new NoSuchElementException();}}public int nextIndex() {return cursor;}public int previousIndex() {return cursor-1;}/*******************Setter and Add implementation in iterator **********************/public void set(E e) {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {AbstractList.this.set(lastRet, e); // get parent interface to set elementexpectedModCount = modCount; //modify expectedModCount} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}public void add(E e) {checkForComodification();try {int i = cursor;AbstractList.this.add(i, e);lastRet = -1;cursor = i + 1;expectedModCount = modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}}/************** Return sublist with beginning index and ended index ***************/public List<E> subList(int fromIndex, int toIndex) {return (this instanceof RandomAccess ?new RandomAccessSubList<>(this, fromIndex, toIndex) :new SubList<>(this, fromIndex, toIndex));}//Use iterator for comparasionpublic boolean equals(Object o) {if (o == this)return true;if (!(o instanceof List))return false;ListIterator<E> e1 = listIterator();ListIterator e2 = ((List) o).listIterator();while (e1.hasNext() && e2.hasNext()) {E o1 = e1.next();Object o2 = e2.next();if (!(o1==null ? o2==null : o1.equals(o2)))return false;}return !(e1.hasNext() || e2.hasNext());}/******************** Learn more about hashcode algorithm ********************/public int hashCode() {int hashCode = 1;for (E e : this)hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());return hashCode;}/******************* Remove elements by range *******************/protected void removeRange(int fromIndex, int toIndex) {ListIterator<E> it = listIterator(fromIndex);for (int i=0, n=toIndex-fromIndex; i<n; i++) {it.next();it.remove();}}protected transient int modCount = 0; // notice the transient keywordprivate void rangeCheckForAdd(int index) {if (index < 0 || index > size())throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+size();}}
// Doesn't support random access, but similar with linked list which is also the abstract class for linkedlistpublic abstract class AbstractSequentialList<E> extends AbstractList<E> {protected AbstractSequentialList() {//提供一个空的默认构造函数}/****************** Through Iterator to achieve getter and setter ******************/public E get(int index) {try {return listIterator(index).next();} catch (NoSuchElementException exc) {throw new IndexOutOfBoundsException("Index: "+index);}}public E set(int index, E element) {try {ListIterator<E> e = listIterator(index);E oldVal = e.next();e.set(element);return oldVal;} catch (NoSuchElementException exc) {throw new IndexOutOfBoundsException("Index: "+index);}}/********************** Add and Remove by Iterator ************************/public void add(int index, E element) {try {listIterator(index).add(element);} catch (NoSuchElementException exc) {throw new IndexOutOfBoundsException("Index: "+index);}}public E remove(int index) {try {ListIterator<E> e = listIterator(index);E outCast = e.next();e.remove();return outCast;} catch (NoSuchElementException exc) {throw new IndexOutOfBoundsException("Index: "+index);}}public boolean addAll(int index, Collection<? extends E> c) {try {boolean modified = false; // mark the modifiedListIterator<E> e1 = listIterator(index);Iterator<? extends E> e2 = c.iterator();while (e2.hasNext()) {e1.add(e2.next());modified = true;}return modified;} catch (NoSuchElementException exc) {throw new IndexOutOfBoundsException("Index: "+index);}}/***************** Iterator Part ********************/public Iterator<E> iterator() {return listIterator();}//Bidrectional Iteratorpublic abstract ListIterator<E> listIterator(int index);}