Java 按排序顺序将元素插入数组

Java 按排序顺序将元素插入数组,java,arrays,sorting,Java,Arrays,Sorting,我已经为在数组中插入和删除元素编写了这段代码。但我想按排序顺序将元素插入数组。如何改进我的添加方法?我也不知道remove方法的实现。如何实现remove方法 public void add(int index, String str) { // First make sure the index is valid. if (index > elements || index < 0) { thr

我已经为在数组中插入和删除元素编写了这段代码。但我想按排序顺序将元素插入数组。如何改进我的添加方法?我也不知道remove方法的实现。如何实现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;
    }

填充数组后,调用:

 Arrays.sort(array)
您正在调整数组的大小,为什么不直接使用列表呢

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

我想您不应该在添加元素时对数组进行排序,而是在返回元素时进行排序。为了减少数组访问,您可以使用标志来指示必须重新使用数组,即

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;
}

这是一般的想法,但可以随意采用。

插入元素后,对数组进行排序。最后,你需要排序数组。这可能会有帮助。你应该使用泛型和你自己的compareTo方法。