标签:for set turn ring time except final 抛出异常 class
手工实现ArrayList第二版:public class he<E> {
private int size;
private static final int DEFAULT_CAPACITY=10;
private Object[] ob;
public he()//无参默认构造
{
ob=new Object[DEFAULT_CAPACITY];
}
public he(int capacity) //有参默认构造
{
ob=new Object[capacity];
}
public void add(E obs)//添加元素和扩容
{
if(size==ob.length)
{
Object[] newArray=new Object[ob.length+ob.length/2];
System.arraycopy(ob,0, newArray, 0, ob.length);
ob=newArray;
}
ob[size++]=obs;
}
public E get(int nums) //返回索引元素
{
if(nums<0||nums>=size)
{
throw new RuntimeException("索引错误");
}
return (E)ob[nums];
}
public void set(int index,E obs) //修改元素
{
if( index<0||index>=size)
{
throw new RuntimeException("索引错误2");
}
ob[index]=obs;
}
public void checkIndex(int index) //检查索引异常
{
if(index<0||index>=size)
{
throw new RuntimeException("索引错误3");
}
}
public void rem(E obs) //通过值移除
{
for(int i=0;i<size;i++)
{
if(ob[i].equals(obs))
{
rem(i);//调用定义好的索引移除方法
}
}
}
public void rem(int index) //通过索引移除
{
if(index<0||index>=size)
{
throw new RuntimeException("索引错误4");
}
System.arraycopy(ob, index+1,ob, index, ob.length-1-index);
ob[--size]=null;
}
public int size() //返回元素个数
{
return size;
}
public String toString() //重写toString方法,直接打印数组名会打印地址
{
StringBuilder s=new StringBuilder();
s.append("[");
for(int i=0;i<size;i++)
{
s.append(ob[i]+",");
}
s.setCharAt(s.length()-1, ‘]‘);
return s.toString();
}
public static void main(String[]args) {
he<String> h=new he<>(20);
}
}
标签:for set turn ring time except final 抛出异常 class
原文地址:https://blog.51cto.com/14437184/2419513