下面是ArrayList
package charpter3;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyArrayList <AnyType> implements Iterable<AnyType> {
private static final int DEFAULT_CAP = 10;
private int theSize ;
private AnyType [] theItems ;
public MyArrayList(){
clear() ;
}
public void clear (){
theSize =0;
ensureCap(DEFAULT_CAP);
}
public boolean isEmpty (){
return size()==0;
}
public void trimToSize(){
ensureCap(size()) ;
}
public AnyType get(int idx){
if (idx<0|| idx>= size())
throw new ArrayIndexOutOfBoundsException();
return theItems[idx] ;
}
/**
* 返回了原来的值
*/
public AnyType set(int idx, AnyType newVal ){
if (idx<0|| idx>=size())
throw new ArrayIndexOutOfBoundsException() ;
AnyType old = theItems[idx] ;
theItems[idx] = newVal ;
return old ;
}
public int size(){
return theSize ;
}
public void ensureCap(int newCap){
if (newCap<theSize)
return ;
AnyType [] old = theItems ;
theItems = (AnyType[]) new Object[newCap] ;
for (int i=0;i<size() ; i++){
theItems[i] = old[i];
}
}
public boolean add (AnyType x ){
add(size(), x);
return true ;
}
public void add(int idx ,AnyType x ){
if (theItems.length== size())
ensureCap(size()*2+1);
for (int i = theSize;i>idx;i--){
theItems[i]= theItems[i-1]; //向后移动
}
theItems[idx] = x;
theSize++;
}
public AnyType remove (int idx){
AnyType removedItem = theItems[idx] ;
for (int i=idx ;i<size()-1 ; i++){ //后面的前移
theItems [i] =theItems[i+1] ;
}
theSize --;
return removedItem ;
}
public Iterator<AnyType> iterator() {
// TODO Auto-generated method stub
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator<AnyType>{
private int current =0;
public boolean hasNext() {
// TODO Auto-generated method stub
return current<size();
}
public AnyType next() {
if (!hasNext()){
throw new NoSuchElementException() ;
}
return theItems[current++];
}
@Override
public void remove() {
MyArrayList.this.remove(--current) ;
}
}
}
这个实现里面的ArrayListIterator是一个内部类,这里分析下内部类与嵌套类。
一.什么是嵌套类和内部类
可以在一个类的内部定义另一个类,这种类称为嵌套类(nested classes),它有两种类型:静态嵌套类和非静态嵌套类。静态嵌套类使用很少,最重要的是非静态嵌套类,也即是被称作为内部类(inner)。嵌套类从JDK1.1开始引入。其中inner类又可分为三种:
其一、在一个类(外部类)中直接定义的内部类;
其二、在一个方法(外部类的方法)中定义的内部类;
其三、匿名内部类。
下面,我将说明这几种嵌套类的使用及注意事项。
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
为什么使用嵌套类(什么时候使用嵌套类):
静态嵌套类的(static nested class):
非静态嵌套类(内部类inner class):
原文:http://www.cnblogs.com/chuiyuan/p/4452024.html