我需要製作自己的數據結構,並且其中一部分正在執行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]);
}
}
}
「我需要製作自己的數據結構」爲什麼?你知道提供的數組列表的來源是[visible](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/ArrayList.java/ )? – 2016-12-30 18:17:28
可能是一項任務 – 2016-12-30 18:18:03
您有一個循環,其目的是轉移元素。循環體將爲您需要移位的每個元素執行一次。你不想每次換一個都創造一個新的元素,是嗎?所以添加新元素的代碼需要移出循環。 – ajb