JAVA仿写ArrayList
程序员文章站
2024-01-07 21:36:46
功能 Object get(int index); 获取该位置数据 boolean add(Object obj); 添加数据 void set(int index, Object obj); 替换该位置数据 boolean remove(int index); 清除该位置数据 boolean isEmpty(); list是否为空 boolean isFull(); list是否已满 int size(); 返......
功能
- Object get(int index); 获取该位置数据
- boolean add(Object obj); 添加数据
- void set(int index, Object obj); 替换该位置数据
- boolean remove(int index); 清除该位置数据
- boolean isEmpty(); list是否为空
- boolean isFull(); list是否已满
- int size(); 返回当前list大小
- void clear(); 清除list中所有数据
- void show();遍历显示list内容
- void extend(); list扩容
代码:
//接口
package copyList;
public interface List {
Object get(int index);
boolean add(Object obj);
void set(int index, Object obj);
boolean remove(int index);
boolean isEmpty();
boolean isFull();
int size();
void clear();
}
//实现
package copyList;
import java.util.Arrays;
public class MyArrayList implements List {
// 数组默认大小
private static int Length = 0;
// 数组下标
private static int tag = 0;
// 核心数组
private static Object[] obj;
public void show() {
if (obj==null) {
System.out.println("当前ArrayList空");
}else {
for (Object object : obj) {
if (object==null) {
continue;
}else {
System.out.print(object + " ");
}
}
System.out.println();
}
}
@Override
public Object get(int index) {
if (obj[index]==null) {
System.out.print("当前位置没有数据,返回 ");
}
return obj[index];
}
@Override
public boolean add(Object object) {
if (isFull()||isEmpty()) {
extend();
}
obj[tag] = object;
tag++;
return false;
}
private void extend() {
if (Length==0) {
obj = new Object[10];
Length = 10;
}else if (isFull()) {
Length = (Length>>1)+Length;
obj = Arrays.copyOf(obj, Length);
}
}
@Override
public void set(int index, Object obj) {
this.obj[index] = obj;
}
@Override
public boolean remove(int index) {
for (int i = index; i < tag; i++) {
obj[index] = obj[index+1];
index++;
}
tag--;
return true;
}
@Override
public boolean isEmpty() {
return obj==null ? true:false;
}
@Override
public boolean isFull() {
return tag==Length ? true:false;
}
@Override
public int size() {
return tag;
}
@Override
public void clear() {
obj = null;
Length = 0;
tag = 0;
}
}
示例:
本文地址:https://blog.csdn.net/qq_35697978/article/details/107694171