I want to know how to insert a new element in Array. I tried but could not succeed. I failed in indexing the new location to Array because Array is of fixed size.
So can you please give the simple example so that I can learn.
5 replies to this topic
#1
Posted 31 March 2011 - 07:02 AM
|
|
|
#2
Posted 31 March 2011 - 08:12 AM
String[] arrayofstrings = new String[3]; arrayofstrings[0] = "we"; arrayofstrings[1] = "something"; arrayofstrings[2] = "bla";
If you want to insert an item after the limit, you can't, you have to recopy your array in a bigger array, there's a class that can do that for you : Vector.
import java.util.Vector;
Vector<String> strings = new Vector<String>();
strings.add("bla");
strings.add("wefw");
strings.add("etc");
#3
Posted 31 March 2011 - 08:45 AM
Without List kind of classes:
import java.util.Arrays;
public class SomeClass{
int[] intArray;
public void addNumber(int number){
intArray = Arrays.copyOf(intArray, intArray.length+1);
intArray[ intArray.length-1 ] = number;
}
}
#4
Posted 31 March 2011 - 01:36 PM
A Vector would be more efficient than the snippet from wim DC because the Vector class does not recopy the array every time you add a item. The way it works, when you add an item, it doubles the size of the array. I'm sure you could easily update his little snippet.
#5
Posted 31 March 2011 - 03:00 PM
Simonxz said:
A Vector would be more efficient than the snippet from wim DC because the Vector class does not recopy the array every time you add a item. The way it works, when you add an item, it doubles the size of the array. I'm sure you could easily update his little snippet.
It is true that it is more efficient to NOT copy the array every time you add an element to the array.
However...
When the objects inside of vector reach initial Capacity +1 the array is doubled and the original array also has to be copied.
If you know more-or-less how many elements the array will contain before-hand, then you have a better chance of knowing what kind of array you should use.
#6
Posted 31 March 2011 - 04:04 PM
It's no secret using a array will always be more efficient than using a vector but his question was about adding an item after the initial capacity is reached
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top









