public class MyArrayList {
//自己编写一个MyArrayList
//1.MyArrayList底层也是一个Object类型的数组:
Object[]value;
//2.数组中被使用的数量:
int count;
//3.空构造器
public MyArrayList() {
//value = new Object[10];
this(10 );
}
//有参构造器
public MyArrayList(int length) {
value =new Object[length];
}
//4.添加add方法:
public void add(Object o) {
value[count] = o;
count++;
//进行数组扩容
if (count >=value.length ) {
//扩容:有新数组
//扩容方式1:Object[] newObj = Arrays.copyOf( value,20);
//扩容方式2:
Object[] newObj =new Object[value.length *2 +1];
//将老数组的东西 复制 到新数组中:
for (int a =0;a <=value.length -1;a++){
newObj[a] =value[a];
}
//将value的指向:指向新的数组:
value = newObj;
}
}
//重写toString
@Override
public StringtoString() {
StringBuilder sb =new StringBuilder();
sb.append("[" );
for (int a =0; a <=count -1; a++) {
sb.append(value[a] +"," );
}
sb.setCharAt( sb.length() -1, ']' );//返回索引位置的元素
return sb.toString();
}
//增加计算数组中元素数量的方法:
public int size() {
return count;
}
//判断是否为空
public boolean isEmpty() {
return count ==0;
}
public static void main(String[] args) {
//创建一个我自定义的数组对象;
MyArrayList list =new MyArrayList();//底层数组长度为10
list.add(10 );
list.add("sdd" );
list.add(15 );
list.add(10 );
list.add(10 );
list.add(10 );
list.add(10 );
list.add(10 );
list.add(10 );
list.add(10 );
list.add(10 );
list.add(10 );
System.out.println( list );
System.out.println("集合中元素的长度;" + list.size() );
System.out.println( list.isEmpty() );
}
}