[英]Adding a value at an index in an array list
我需要建立自己的數據結構,其中一部分是執行ArrayList。 我需要確保可以在元素n處添加一個對象,同時向下推所有其他對象。 這是我的代碼。 現在,它將元素添加兩次。 它是函數public ReturnObject add(int index,Object item)。 我需要此函數在指定的索引處添加對象,然后將其他對象向下移動。
public class ArrayList implements List{
public static final int CAPACITY=16;
private int size = 0;
private Object[] data;
ReturnObjectImpl ro;
//constructors
public ArrayList() {
data = new Object[CAPACITY];
} //CONSTRUCTS LIST WITH DEFAULT CAPACITY
public ArrayList(int capacity) { // constructs list with given capacity
data = new Object[capacity];
System.out.println("Created an ArrayList of capacity " + capacity);
}
public boolean isEmpty(){
if(size == 0) {
// System.out.println("The list is empty");
return true;
}
return false;
}
public int size(){
System.out.println("The ArrayList is not full, but currently has " + size + " indexs");
return size;
}
public ReturnObject get(int index){
ro = new ReturnObjectImpl(data[index]);
return ro;
}
public ReturnObject remove(int index){
return null;
}
public ReturnObject add(int index, Object item){
if(index <= size && index < data.length){
for (int x = size-1; x >= index; x--){
data[x+1] = data[x];
data[index] = item;
ro = new ReturnObjectImpl(data[index]);
size++;
}
System.out.println("Added to array at " + index);
}
return ro;
}
public ReturnObject add(Object item){
if (data[0] == null){
data[0] = item;
}
//int adding = size + 1;
data[size] = item;
System.out.println("Added item to index " + size);
size++;
return null;
}
//added - but DELETE BEFORE SUBMITTING
public void printAll(){
for(int x = 0; x < data.length; x++){
System.out.println(data[x]);
}
}
}
顯然,將對象插入該數組時:
for (int x = size-1; x >= index; x--){
data[x+1] = data[x];
data[index] = item;
不應該在一個循環中發生! 插入應該只在正確的索引處發生一次! 因此,即使您保留該循環來移動其他元素,“移動循環” 結束 之后也應該進行最后一次分配。
因此,重點是:您應該退后一步,並仔細查看此循環及其循環變量的作用。
換句話說:要么拿一張紙,然后自己“運行”代碼;要么 或在調試器中運行它。
由於這可能是某種家庭作業,因此我將其保留下來。 它應該足夠使您前進並幫助您修復代碼。
除了GhostCat的answer之外,也可以使用System.arrayCopy()
來將右側的部分“移動”到右側,而不是for
循環。 您只需要知道內部陣列( data
)是否已滿。 如果是,則必須擴展內部陣列。
System.arraycopy(this.data, insertIndex, this.data, insertIndex + 1, 1);
一些注意事項:
編碼
if (data[0] == null) { data[0] = item; }
如果調用了ArrayList(0)
,將拋出ArrayIndexOutOfBoundsException
。
編碼
if (size == 0) { // System.out.println("The list is empty"); return true; } return false;
可以重寫為
return (size == 0);
您似乎省略了更多檢查,例如檢查內部陣列是否已滿。 您當前的代碼不會擴展內部數組,因此,如果添加的對象超過了初始容量(默認值為16),則將引發ArrayIndexOutOfBoundsException
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.