表的顺序结构---重写Arraylist类
2013-10-12 17:25
423 查看
重写ArrayList类,为防止冲突,重写为MyArrayList,未继承Iterable类。
public class MyArrayList<AnyType>{ int N=10; AnyType a[]; //定义一个数组,未分配空间 int theSize; public MyArrayList(){ clear(); } public void clear(){ theSize=0; increaseSpace(N); //对数组初始化,扩容为10 } public int size(){ //返回顺序表长度 return theSize; } public boolean isEmpty(){ //判断顺序表是否为空 if(size()==0) return true; return false; } public AnyType get(int index){ //获取下标为index的数据 if(index<0||index>=size()){ //判断所查找的数据是否存在, return null; } return a[index]; } public AnyType set(int index,AnyType x){ //用X替换表中某一数据,并返回被替换的值 if(index<0||index>=size()){ return null; } AnyType old=a[index]; a[index]=x; return old; } public void increaseSpace(int newSpace){ //扩容 //if(newSpace<theSize) //return; AnyType b[]=a; a=(AnyType[]) new Object[newSpace]; //???? for(int i=0;i<size();i++){ a[i]=b[i]; } } public boolean add(AnyType x){ //添加元素 add(size(),x); return true; } public void add(int index,AnyType x){ //在指定位置插入元素 if(a.length==size()) //判断是否需要扩容 increaseSpace(size()*2); for(int i=size();i>index;i--){ //把index位置后的元素从右向左依次右移,并使theSize加一 a[i]=a[i-1]; } a[index]=x; theSize++; } public AnyType remove(int index){ //删除表中指定位置的元素 AnyType r=a[index]; for(int i=index;i<size()-1;i++){ //将index位置后的元素从左向右依次左移,并使theSize减一 a[i]=a[i+1]; } theSize--; return r; } public static void main(String[] args) { MyArrayList<String> m=new MyArrayList<String>(); m.add(0,"aaa"); System.out.println(m.size()+" "+m.get(0)); m.add(1,"bbb"); System.out.println(m.size()+" "+m.get(1)); m.add(2,"ccc"); System.out.println(m.size()+" "+m.get(2)); m.add(3,"ddd"); System.out.println(m.size()+" "+m.get(3)); m.set(2,"eee"); System.out.println(m.size()+" "+m.get(2)); m.remove(1); System.out.println(m.size()+" "+m.get(1)); m.set(8,"fff"); System.out.println(m.size()+" "+m.get(4)); System.out.println(m.isEmpty()); } }
相关文章推荐
- 表的顺序结构---重写Arraylist类
- MC新手入门(二十八)------ 顺序结构程序
- 线性表的顺序表示和实现 - 数据结构
- 二叉树顺序结构
- C语言实验——转换字母(顺序结构)
- oj1949: C语言实验——转换字母(顺序结构)
- 数据结构之顺序表的基本操作
- 数据结构基础(2) --顺序查找 & 二分查找
- 数据结构--顺序栈基本功能实现程序…
- SDUT-JAVA语言实验——转换字母(顺序结构)
- 数据结构——线性表之顺序存储学习
- 线性表——顺序结构(c语言实现)
- 四种数据存储结构---顺序存储 链接存储 索引存储 散列存储
- 如何改变oracle表结构列顺序
- 【数据结构】顺序栈的基本操作
- 数据结构实验之查找六:顺序查找
- 画uml图、流程图、软件结构图、类图、顺序图的方法
- 数据结构之线性表--顺序存储
- 数据结构与算法(线性表_顺序表存储结构)
- C语言实验——计算A+B(顺序结构)