数据结构:顺序表(java版本带迭代器)

package Unit3表栈队列;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.jar.JarException;
import java.util.Scanner;
//import com.sun.tools.javac.code.Type.ForAll;

public class MyArrayList<T>{
	private final int max_size=10;
	private int thesize;//记录当前数组元素的个数
	private T[]arr;//记录数组元素
	public MyArrayList() {
		thesize=0;
		doClear();
	//	System.out.println(thesize);
	}//新建MyArrayList对象
	private void doClear() {
		thesize=0;//
		ensuresize(max_size);
	}
	public void clear() {
        doClear();
	}
	public int size() {
		return thesize;//返回当前数组元素个数
	}
	public boolean isEmpty() {
		return size()==0;//判断是否为空
	}
	public T get(int idx) {
		if(idx<0||idx>=thesize)
			throw new ArrayIndexOutOfBoundsException();
		return arr[idx];
	}
	public T set(T newval,int idx) {
		if(idx<0||idx>=thesize)
			throw new ArrayIndexOutOfBoundsException();//抛出数组越界异常
		T old=arr[idx];
		arr[idx]=newval;
		return old;
	}
	public void trimsize()
	{
		ensuresize(size());//将MyArrayList的大小改为thesize
	}
	public void add(T newval) {
		if(arr.length==size()) {
			ensuresize(2*size()+1);
		}
		arr[thesize++]=newval;
		
	}
	public void add(int idx,T newval) {
	//	System.out.println(thesize);
		if(arr.length==size()) {
			ensuresize(2*size()+1);
		    for(int i=thesize;i>idx;i--)
		    	arr[i]=arr[i-1];
		    arr[idx]=newval;
		    thesize++;
		    System.out.println(thesize+"--------");
		}
	}
	public void ensuresize(int newsize) {
		if(newsize<thesize)
			return;
		T []old=arr;
		arr=(T [])new Object[newsize];
	    for(int i=0;i<size();i++)
	    	arr[i]=old[i];
	   // thesize=newsize;
	}
	public T remove(int idx) {
		T old=arr[idx];
		for(int i=idx;i<thesize-1;i++)
			arr[i]=arr[i+1];
		thesize--;
		return old;
	}
	public Iterator iterator(){
		return new MyArrayListIterator();
	}
	private class MyArrayListIterator implements Iterator{
		private int current=0;
		public boolean hasNext() {
			if(current<size())
			return true;
			return false;
		}
		public T next() {
			if(!hasNext()) {
				throw new NoSuchElementException();
			}
			return arr[current++];
		}
		public void remove() {
			MyArrayList.this.remove(--current);
		}
		
	}
	public static void main(String []args) {
		Scanner cin=new Scanner(System.in);
		MyArrayList<Integer>arrayList=new MyArrayList<Integer>();
		for(int i=0;i<5;i++) {
			arrayList.add(cin.nextInt());
		}
		Iterator it=arrayList.iterator();
		while(it.hasNext())
			System.out.println(it.next());
		System.out.println(arrayList.size());
		arrayList.remove(0);
		it=arrayList.iterator();
		while(it.hasNext())
			System.out.println(it.next());
		//for(Integer i:arrayList)
		//	System.out.println(i);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值