0
public class MyArrayList<T> implements MyList<T>{
int num; //number of things in the list
T[] vals; //to store the contents
@SuppressWarnings("unchecked")
public MyArrayList() {
num = 0;
vals = (T[]) new Object[3];
}
public int size() { //returns number of things in the bag
return num;
}
public T get(int index) { //returns the indexth values
if((index < 0) || (index >= num))
throw new IndexOutOfBoundsException();
return vals[index];
}
@SuppressWarnings("unchecked")
public void add(T s) { //adds s to the list
if(num == vals.length) { //if array is full, make it bigger
T[] temp = (T[]) new Object[vals.length*2];
for(int i=0; i < num; i++)
temp[i] = vals[i];
vals = temp;
}
vals[num] = s;
num++;
}
public boolean contains(T s) { //returns whether s is list
for(int i=0; i < num; i++) { //ending condition should be num
if(vals[i].equals(s)) {
return true;
}
}
return false;
}
public T getUnique(){
T distinct = null;
int count = 0;
for (int i=0; i<vals.length; i++){
distinct = vals[i];
for (int j = 0; j<vals.length; j++){
if (vals[j] == vals[i]){
count++;
}
if (count == 1){
return distinct;
}
}
}
if (distinct == null){
throw new IllegalArgumentException();
}
return distinct;
}
public void addBefore(T input, T before){
for (int i = 0; i<vals.length; i++){
T temp = vals[i];
if(temp.equals(before)){
vals[i-1] = input;
}
}
}
public void removeLast(T s){
for (int i = vals.length; i>=0;i--){
if (vals[i].equals(s)){
vals[i] = vals[i+1];
}
}
}
}
我正在研究Java中的ArrayList實現。我無法完成getUnique,removeLast和addBefore方法。我似乎無法與數組配合,因爲我似乎一直在替換值而不是添加它。對我在做什麼錯了一點幫助。在Java中實現ArrayList。致力於getUnique,addBefore和removeLast
我該如何將列表的剩餘部分向右移動? –
這不是微不足道的,你將不得不創建新的列表添加元素。首先,您將添加這些位於要添加的元素之前的元素,然後添加新元素,然後添加列表的其餘部分。 – SILL
所以你的意思是我將創建一個臨時列表並添加它像這樣? –