使用对象数组手动实现ArrayList添加方法



你好,我需要手动实现一个arraylist.add()方法,只使用数组和一个数组复制方法,但我很难做到这一点。该方法的规范是,该方法在指定位置插入一个元素,并将当前位于该位置的任何元素向右移动,并将一添加到索引中,将数组的大小扩展一,以使所有元素都适合。有人请帮忙。

    private Object [] list;
    final int maxObjects = 100;
    public ListOfObjects()
    {
        list= new Object[maxObjects];
    }
    public ListOfObjects(Object[]o)
    {
        list= o;
    }
    public void add(Object element,int index)
    {
        Object[] newData = new Object[list.length+1];
        for(int i =0; i < index; i++)
        {
            newData[i] = list[i];
            newData[list] = element;
        }
        for(int i = index; i < list.length; i++)
        {
            newData[i+1] = list[i];
        }
    }

将元素添加到对象数组的索引中

Object[] myObjects;
public static void addObject(Object obj, int index) {
// Assuming you want something in your empty array
     if(myObjects == null) {
        myObjects = new Object[] { obj };
        return;
    } 
    ArrayList<Object> temp = new ArrayList<Object>();
    for(int i = 0; i < myObjects.length; i++) { 
        if(i == index)
           temp.add(obj);
        temp.add(myObjects[i]);
    }
    myObjects = temp.toArray(new Object[temp.size()]);
}

System.arrayCopy的javadoc专门谈到src和dest是同一数组的情况:

如果src和dest参数引用相同的数组对象,则执行复制,就好像在位置srcPos到srcPos+length-1首先被复制到一个长度为的临时数组组件,然后复制临时数组的内容到destPos到destPos+目的地长度-1的位置大堆

如果备份list的大小足够,则只需使用arrayCopy将受影响的索引移动到1以上。

//shift everything after the index over
System.arrayCopy(list, index, list, index + 1, list.length - index);
//place new value in index
list[index] = element;

否则,您需要创建一个新数组,然后使用arrayCopy在插入索引之前复制所有内容。

Object[] newList = new Object[calcSize()];
//first copy everything before index if index is not 0
if (index > 0)
{
    System.arrayCopy(list, 0, newList, 0, index);
}
newList[index] = element;
System.arrayCopy(list, index, newList, index+1, list.length - index);

你的逻辑在我看来是错误的。你应该做一些类似-的事情

    Object[] newData = new Object[list.length+1];
    for(int i =0; i < index; i++)
    {
        newData[i] = list[i];
    }
    newData[index] = element;
    for(int i = index; i < list.length; i++)
    {
        newData[i+1] = list[i];
    }

此解决方案利用了ArrayList迭代器,该迭代器按正确的顺序返回对象:

    ArrayList<Object> elementInserter(ArrayList<Object> inArray, Object element, int index){
       ArrayList<Object> outArray = new ArrayList<Object>(inArray.size() + 1);
       outArray.addAll(inArray.subList(0, index));
       outArray.add(element);
       outArray.addAll(inArray.subList(index, inArray.size()));
       return outArray;
   }

最新更新