2014-11-06 122 views
0

我已經編寫了用於插入和從數組中移除元素的代碼。但我想按排序順序將元素插入到數組中。我該如何改進我的「添加」方法?我也不知道「刪除」方法的實施。我怎樣才能實現remove方法按排序順序將元素插入到數組中

public void add(int index, String str) { 
      // First make sure the index is valid. 
      if (index > elements || index < 0) { 
       throw new IndexOutOfBoundsException(); 
      } 

      // If the list is full, resize it. 
      if (elements == list.length) { 
       resize(); 
      } 

      // Shift the elements starting at index 
      // to the right one position. 
      for (int index2 = elements; index2 > index; index2--) { 
       list[index2] = list[index2 - 1]; 
      } 

      // Add the new element at index. 
      list[index] = str; 

      // Adjust the number of elements. 
      elements++; 
     } 
public boolean remove(String str) { 


     return false; 
    } 
+0

插入元素對數組進行排序後。最後你想要排序的數組。 – Visme 2014-11-06 12:29:36

+2

看[這裏](http://stackoverflow.com/questions/8725387/why-there-is-no-sortedlist-in-java)mybe這有助於。 – Jens 2014-11-06 12:29:41

回答

0

填充陣列後,致電:

Arrays.sort(array) 

所調整的陣列,你爲什麼不乾脆用一個列表?

List<Type> list = new ArrayList<Type>(); 
Collections.sort(list); 
0

我想你應該排序數組而不是添加元素,但是當你返回它。爲了減少數組訪問您可以使用標誌,這將表明,陣列必須使出,即

private boolean hasNew = false; 

public void add (int index, String str) { 
    // Your code 
    hasNew = true; 
} 

public int[] getArray() { 
    if (hasNew) Arrays.sort(list); 
    return list; 
} 

這是一般的想法,但隨時採納。

+0

不適用於字符串列表 – 2014-11-06 12:46:16

+0

您應該使用泛型和您自己的compareTo()方法。 – wanderlust 2014-11-06 13:17:18