0

I have written this code for insert and remove elements into and from array. But I want to insert elements into array in sorted order. How can I improve my "add" method? And I also don't know the implementation of the "remove" method. How can I implement remove method

    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;
    }
Bhumi Patel
  • 21
  • 1
  • 9
  • after insert elements sort the array. finally u want sorted array. – Visme Nov 06 '14 at 12:29
  • 2
    Look [here](http://stackoverflow.com/questions/8725387/why-there-is-no-sortedlist-in-java) mybe this helps. – Jens Nov 06 '14 at 12:29

2 Answers2

0

After filling the array, call:

 Arrays.sort(array)

You are resizing the array, why dont you simply use a List?

List<Type> list = new ArrayList<Type>();
Collections.sort(list);
Stefan
  • 12,108
  • 5
  • 47
  • 66
0

I suppose you should sort array not on adding element but when you return it. For decreasing array accesses you may use flag that will indicate that array must be resorted, i.e.

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

This is the general idea, but feel free to adopt it.

wanderlust
  • 1,826
  • 1
  • 21
  • 25