• 表的顺序结构---重写Arraylist类


    重写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());
            
    	}
    
    }
    

  • 相关阅读:
    关于idea的目录, mybatis里mapper无法用resource获取 和 驼峰命令规则
    直接调用类方法 和 new再调用方法 的区别
    腾讯笔试题
    linux安装包
    centos 学习笔记一
    putty链接l虚拟机linux centos
    单链表的一般处理(C语言)
    华为2011机试题
    【转】函数返回类型为指针类型时的一些问题
    在 Windows Server 2012 上安装 dotNET Framework v3.5
  • 原文地址:https://www.cnblogs.com/oversea201405/p/3752281.html
Copyright © 2020-2023  润新知