上周发了LinkList的才想起ArrayList的没发,特来补上~
ArrayList底层是基于数组实现的:根据索引定位元素快,增删需要做元素的移位操作。
下面是ArrayList的简单实现。
public class MYArrayList1 {
Object[] list = {};
private int size;
public MYArrayList1() {//调用无参就是集合大小为10;
this.list = new Object[10];
}
public MYArrayList1(int j) {//调用有参就是集合大小为你设定的值;
this.list = new Object[j];
}
public void add(Object A) {//Arryslist增加元素的方法简单来说就是,我们先设定一个指针,这个指针的作用就是跟着集合长度走
//开始指针为0嘛,然后我们用集合长度去跟指针做个if判断,如果指针值小于数组长度就是一直把1添加的值直接赋值给集合,不大于的时候我们直接
//扩容集合大小为原来2倍,再添加,if结束后别忘1size++;
if (size < list.length) {
list[size] = A;
} else {
list = Arrays.copyOf(list, list.length * 2);
list[size] = A;
}
size++;
}
public int found(Object A) {//查找索引
int index = -1; // 初始化为-1,表示未找到
for (int i = 0; i < list.length; i++) {
if (A.equals(list[i])) {
index = i;
break; // 找到后直接退出循环
}
}
return index;
}
public void remove(Object A) {//删除
int del = found(A);
if (del != -1) { // 如果找到了要删除的对象
for (int i = del; i < size; i++) {
list[i] = list[i + 1];
}
size--; // 更新列表大小
list[size] = null; // 将最后一个元素置空
} else {
System.out.println("Object not found!"); // 如果未找到要删除的对象,则输出提示信息
}
}
public void set(int a,Object A){//修改第几个元素的值
if (a>= 0 && a < size) {
list[a] = A;
} else {
throw new IndexOutOfBoundsException("Index out of bounds!");
}
}
public Object get(int a){//查看第几个元素的值
if(a>0&&a<size){
return list[a];
}
else {
throw new IndexOutOfBoundsException("Index out of bounds!");
}
}
@Override
public String toString() {
return "MYArrayList{" +
"list=" + Arrays.toString(list) +
", size=" + size +
'}';
}
public static void main(String[] args) {
MYArrayList1 list2 = new MYArrayList1();
list2.add(1);
list2.add(2);
System.out.println(list2);
list2.remove(1); // 删除对象1
System.out.println(list2);
}
}
喜欢务必点赞收藏支持一下,谢谢各位看官老爷!
本文详细介绍了Java中的ArrayList类,包括其基于数组的底层实现、快速索引、增删元素的操作过程以及查找、删除和修改元素的方法。
437

被折叠的 条评论
为什么被折叠?



