JAVA自定义容器—自动扩容—查找—删除 代码实现

 1 package cn.itsource._05IntArry;
 2 
 3 import java.util.Arrays;
 4 
 5 public class IntArry {//容器类
 6     Object[] date;//定义Object的数组
 7     int size;//size表示存值的个数
 8     int capacity;//容器的大小
 9     IntArry(){//无参构造方法 默认这个容器大小16
10         this(16);
11     }
12     
13     IntArry(int capacity){
14         this.capacity=capacity;
15         date = new Object[capacity];
16     }
17     
18     public void add(Object obj){//obj表示存入的一个元素
19         if(size>date.length){//判断是否能够放入元素 如果不能 就要扩容
20             Object[] newArry = new Object[size+20];//扩容
21             System.arraycopy(date, 0, newArry, 0, size);//将原数组的数据复制到新数组去
22             date=newArry;//将新数组给date
23         }
24         date[size]=obj;//容量够的时候就放到数组
25         size++;//记录放入数组的个数    
26     }
27     
28     public String toString(){//覆写方法 返回字符串类型的数据
29         Object[] newArry = new Object[size];
30         System.arraycopy(date, 0, newArry, 0, size);
31         return Arrays.toString(newArry);    
32     } 
33     
34     //获取指定索引处元素
35     public Object getElementByIndex(int index){//date属于Object类型
36         indexOut(index);
37         return date[index];
38     }
39     
40     //判断是否超出索引
41     public void indexOut(int index){
42         if(index<0||index>=date.length){
43             throw new ArrayIndexOutOfBoundsException("索引范围为0~"+size+"请重新输入");
44         }
45     }
46     
47     //查找指定元素第一次出现的索引
48     public int firstElementIndex(Object obj){
49         for(int i =0;i<size;i++){
50             if(date[i].equals(obj)){//判断两个元素是否相等
51                 return i;
52             }        
53         }return -1;
54     }
55     
56     //删除指定索引处元素
57     public void delIndexElement(int index){
58         indexOut(index);
59         System.arraycopy(date, index +1, date, index, size-index -1);
60         size--;
61     }
62     
63     //删除指定的第一个元素
64     public void delFirstElementIndex(Object obj){
65         int firstElementIndex=firstElementIndex(obj);
66         delIndexElement(firstElementIndex);    
67     }
68 }

猜你喜欢

转载自www.cnblogs.com/logoman/p/11253496.html