package com.example.demo; import java.util.Arrays; public class ArrayListDemo<T> { private Object[] objects = {}; private int size; public int getSize() { return size; } public boolean add(T t) { if (objects.length == 0) { objects = new Object[1]; } if (objects.length == size) { objects = Arrays.copyOf(objects, size + 1); } objects[size++] = t; return true; } public T get(int index) { if (index<0||index >= size) { throw new ArrayIndexOutOfBoundsException("array index exception"); } return (T) objects[index]; } public boolean remove(int index){ if (index<0||index>=size){ throw new ArrayIndexOutOfBoundsException("array index exception"); } if (index==size-1){ objects[index]=null; }else { for (int i=index;i<objects.length;i++){ objects[index]=objects[index+1]; } } objects=Arrays.copyOf(objects,size-1); return true; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); for (Object o : objects) { stringBuilder.append(o + ","); } String string = stringBuilder.substring(0, stringBuilder.toString().length()-1); string = string + "]"; return string; } public static void main(String[] args) { ArrayListDemo<String> arrayListDemo=new ArrayListDemo<>(); arrayListDemo.add("dsdfs"); arrayListDemo.add("dsdd"); arrayListDemo.add("sdsd"); for(int i=0;i<arrayListDemo.size;i++){ String s=arrayListDemo.get(i); System.out.println(s); } System.out.println(arrayListDemo); } }
手动实现ArrayList
最新推荐文章于 2025-05-03 10:56:02 发布