码迷,mamicode.com
首页 > 编程语言 > 详细

顺序表JAVA代码

时间:2016-05-27 00:33:39      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

 
 
  1. publicclassSeqList{
  2.  
  3.     final int defaultSize =10;     //默认的顺序表的最大长度
  4.     int maxSize;                      //最大长度
  5.  
  6.     int size;                         //当前长度
  7.     Object[] listArray;               //对象数组
  8.  
  9.  
  10.     publicSeqList(){
  11.         init(defaultSize);
  12.     }
  13.  
  14.     publicSeqList(int size){
  15.         init(size);
  16.     }
  17.  
  18.     //顺序表的初始化方法
  19.     privatevoid init(int size){
  20.         maxSize = size;
  21.         this.size =0;
  22.         listArray =newObject[size];
  23.     }
  24.  
  25.     publicvoiddelete(int index) throws Exception
  26.     {
  27.         //容错性
  28.         if(isEmpty()){
  29.             thrownewException("顺序表为空,无法删除!");
  30.         }
  31.         if(index <0|| index > size -1){
  32.             thrownewException("参数错误!");
  33.         }
  34.  
  35.         //移动元素(从前往后操作)
  36.         for(int j = index; j < size -1; j++)
  37.             listArray[j]= listArray[j +1];
  38.  
  39.         listArray[size -1]= null;      //注意释放内存(避免内存泄漏)
  40.         size--;
  41.     }
  42.  
  43.     publicObject get(int index) throws Exception
  44.     {
  45.         if(index <0|| index >= size){
  46.             thrownewException("参数错误!");
  47.         }
  48.  
  49.         return listArray[index];
  50.     }
  51.  
  52.     publicvoid insert(int index,Object obj) throws Exception
  53.     {
  54.  
  55.         //容错性
  56.         if(size == maxSize){
  57.             thrownewException("顺序表已满,无法插入!");
  58.         }
  59.         if(index <0|| index > size){
  60.             thrownewException("参数错误!");
  61.         }
  62.  
  63.         //移动元素(从后往前操作)
  64.         for(int j = size -1; j >= index; j--)
  65.             listArray[j +1]= listArray[j];
  66.  
  67.         listArray[index]= obj;
  68.         size++;
  69.  
  70.     }
  71.  
  72.     public boolean isEmpty(){
  73.         return size ==0;
  74.     }
  75.  
  76.     publicint size(){
  77.         return size;
  78.     }
  79. }
 
 
  1. publicclassTest{
  2.  
  3.     publicstaticvoid main(String[] args){
  4.  
  5.         SequenceListlist=newSequenceList(20);
  6.  
  7.         try{
  8.             list.insert(0,100);
  9.             list.insert(0,50);
  10.             list.insert(1,20);
  11.  
  12.             for(int i =0; i <list.size; i++){
  13.                 System.out.println("第"+ i +"个数为"+list.get(i));
  14.             }
  15.  
  16.         }catch(Exception e){
  17.             e.printStackTrace();
  18.         }
  19.     }
  20. }
 
技术分享
 
 
 





顺序表JAVA代码

标签:

原文地址:http://www.cnblogs.com/Doing-what-I-love/p/5533088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!