java 数组随机访问 性能_快速随机访问和可删除的数组

1 publicclassNoOrderArray2 {3 privateObject[] values=null;4 5 privateintsize=0;6 7 /**8 * 数组 NoOrderArray 的构造函数。 
9 *10 *@paramcapacity int - 数组的初始容量。11 */12 publicNoOrderArray(intcapacity)13 {14 if(capacity<0)15 thrownewIllegalArgumentException("Illegal Capacity:"+capacity);16 17 values=newObject[capacity];18 }19 20 /**21 * 数组 NoOrderArray 的构造函数,初始容量为 8.
22 */23 publicNoOrderArray()24 {25 this(10);26 }27 28 /**29 * 设定数组的容量大小,使其至少满足 minCapacity 所指的大小。 
30 *31 *@paramminCapacity int - 新的容量值。32 */33 publicvoidensureCapacity(intminCapacity)34 {35 intoldCapacity=values.length;36 37 if(minCapacity>oldCapacity)38 {39 Object[] oldValues=values;40 41 intnewCapacity=(oldCapacity*3)/2+1;42 43 if(newCapacity54 *55 *@paramvalue - 添加的内容。56 */57 publicvoidadd(Object value)58 {59 ensureCapacity(size+1);60 61 values[size]=value;62 63 size++;64 }65 66 /**67 * 清除数组 NoOrderArray 中的全部元素。 
68 */69 publicvoidclear()70 {71 //释放内存72 for(inti=0; i80 *81 *@paramindex int - 索引值。82 *83 *@returnObject - 对应的元素。84 */85 publicObject get(intindex)86 {87 if(index>=size||index<0)88 thrownewIndexOutOfBoundsException("Index out of bounds.");89 90 returnvalues[index];91 }92 93 /**94 * 判断当前 NoOrderArray 数组是否为空。 
95 *96 *@returnboolean - 如果为空返回 true.97 */98 publicbooleanisEmpty()99 {100 return(size==0);101 }102 103 /**104 * 移除 NoOrderArray 数组中指定位置的元素。 
105 *106 *@paramindex int - 索引值。107 *108 *@returnObject - 被移除的元素。109 */110 publicObject remove(intindex)111 {112 if(index>=size||index<0)113 thrownewIndexOutOfBoundsException("Index out of bounds.");114 115 Object value=values[index];116 117 if(index!=size-1)118 {119 //将数组最后一个值补充到被移除的位置。120 values[index]=values[size-1];121 }122     values[size - 1] = null; // 防止该位置永久持有对象的引用

123 size--;124 125 returnvalue;126 }127 128 /**129 * 判断指定的数据是否在 NoOrderArray 数组中。 
130 *131 *@paramvalue Object - 需要判断的数据。132 *133 *@returnboolean - 如果包含返回 true.134 */135 publicbooleancontains(Object value)136 {137 if(value==null)138 {139 for(inti=0; i155 *156 *@returnint - 当前数组的大小。157 */158 publicintsize()159 {160 returnsize;161 }162 163 /*164 * (non-Javadoc)165 *166 * @see java.lang.Object#toString()167 */168 publicString toString()169 {170 StringBuffer buffer=newStringBuffer();171 172 buffer.append('[');173 174 for(intindex=0; index0)179 buffer.append(',');180 181 buffer.append(value);182 }183 184 buffer.append(']');185 186 returnbuffer.toString();187 }188 189 /**190 *@paramargs191 */192 publicstaticvoidmain(String[] args)193 {194 //TODO 自动生成方法存根195 }196 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值