Using Arrays

I need to write a method that adds intergers to an array and keeps it in sorted order I have written the following code:

public void add(int value) {

int index = binarySearch(elementData,value,0, size -1);

for (int i = size; i > index; i- -)

{

elementData = elementData[i - 1];

elementData[index + 1] = value;

size++;

}

}

I keep getting the error message that ArrayOutOfBound I understand that this is caused when I try to access an index of the array that does not exist. I can't figure out how to fix this. Can anyone help me?

[607 byte] By [PANa] at [2007-11-27 8:48:47]
# 1

First of all, use the "code" tag, It helps.

Arrays have not dynamic size, so if you NEED to use an array, you will have to create another one, with size + 1, each time method is called.

Then you can copy the data with System.arraycopy() .

I could put the code, but you will be glad to do it by yourself : )

cya.

pbulgarellia at 2007-7-12 20:56:39 > top of Java-index,Java Essentials,New To Java...
# 2

To increase the size of an array dynamically check out the following example

public class Main {

/**

* @param args

*/

public static void main(String[] args) {

//Define an array with 4 elements

String[] names = new String[4];

names[0] = "ana";

names[1] = "ines";

names[2] = "carolina";

names[3] = "alice";

/**

* Now I need to increase the size by one

*/

String anotherName = "sofia";

//Create a temp array

String[] tmp = new String[names.length + 1];

//Copy the array names to the array tmp

System.arraycopy(names, 0, tmp, 0, names.length);

//Copy the referency from the array tmp to the array names

names = tmp;//o array tmp ready for get garbage collected

//Last element is empty. Add the string

names[names.length-1] = anotherName;

//Check the result

for(String name: names)

System.out.println(name);

}

}

Manuel Leiria

manuel.leiriaa at 2007-7-12 20:56:39 > top of Java-index,Java Essentials,New To Java...
# 3
If possible, use Array equivalent such as ArrayList. It is much faster to access and have dynamic size. So that the ArrayIndexOutOfBound error will not happen. ArrayList is preferred for performance concern.
money_0422a at 2007-7-12 20:56:39 > top of Java-index,Java Essentials,New To Java...
# 4

> If possible, use Array equivalent such as ArrayList.

> It is much faster to access and have dynamic size. So

> that the ArrayIndexOutOfBound error will not happen.

> ArrayList is preferred for performance concern.

yes, I agree with you but for simple linear structures the difference is not that much

Manuel Leiria

manuel.leiriaa at 2007-7-12 20:56:39 > top of Java-index,Java Essentials,New To Java...
# 5
It has nothing to do with 'simple linear structure'. It has everything to do with (i) the amount of data and (ii) reusing code that already works. You would have finished by now..
ejpa at 2007-7-12 20:56:39 > top of Java-index,Java Essentials,New To Java...