2017-02-07 10 views
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

回答

0

在addBefore方法中,您正在使用新變量重寫i-1索引上的內容,因此不會添加它。您必須將列表的其餘部分移至右側。也可以嘗試在第一個元素之前添加新的輸入,它會崩潰。

在移除最後您將第二個變量移動到最後一個索引(倒數第二個=最後一個)。你應該只是在最後一個索引上調用remove。

我假設你想返回getUnique方法中的唯一元素。你幾乎在那裏,看看第二個週期。順便說一句,你不需要幫助變量來保存vals [i],你可以返回vals [i]。

+0

我該如何將列表的剩餘部分向右移動? –

+0

這不是微不足道的,你將不得不創建新的列表添加元素。首先,您將添加這些位於要添加的元素之前的元素,然後添加新元素,然後添加列表的其餘部分。 – SILL

+0

所以你的意思是我將創建一個臨時列表並添加它像這樣? –