2014-11-06 84 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