There are many ways to add an element to an array. You can use a temp List
to manage the element and then convert it back to Array
or you can use the java.util.Arrays.copyOf
and combine it with generics for better results.
This example will show you how:
public static <T> T[] append2Array(T[] elements, T element)
{
T[] newArray = Arrays.copyOf(elements, elements.length + 1);
newArray[elements.length] = element;
return newArray;
}
To use this method you just need to call it like this:
String[] numbers = new String[]{"one", "two", "three"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(numbers, "four");
System.out.println(Arrays.toString(numbers));
If you want to merge two array you can modify the previous method like this:
public static <T> T[] append2Array(T[] elements, T[] newElements)
{
T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);
return newArray;
}
Now you can call the method like this:
String[] numbers = new String[]{"one", "two", "three"};
String[] moreNumbers = new String[]{"four", "five", "six"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(numbers, moreNumbers);
System.out.println(Arrays.toString(numbers));
As I mentioned, you also may use List
objects. However, it will require a little hack to cast it safe like this:
public static <T> T[] append2Array(Class<T[]> clazz, List<T> elements, T element)
{
elements.add(element);
return clazz.cast(elements.toArray());
}
Now you can call the method like this:
String[] numbers = new String[]{"one", "two", "three"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
System.out.println(Arrays.toString(numbers));
I've made this code! It works like a charm!
public String[] AddToStringArray(String[] oldArray, String newString)
{
String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
newArray[oldArray.length] = newString;
return newArray;
}
I hope you like it!!
you can create a arraylist, and use Collection.addAll()
to convert the string array to your arraylist
There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.
String[] array1 = new String[]{"one", "two"};
String[] array2 = new String[]{"three"};
String[] array = new String[array1.length + array2.length];
System.arraycopy(array1, 0, array, 0, array1.length);
System.arraycopy(array2, 0, array, array1.length, array2.length);
Size of array cannot be modified. If you have to use an array, you can use:
System.arraycopy(src, srcpos, dest, destpos, length);
If you would like to store your data in simple array like this
String[] where = new String[10];
and you want to add some elements to it like numbers please us StringBuilder which is much more efficient than concatenating string.
StringBuilder phoneNumber = new StringBuilder();
phoneNumber.append("1");
phoneNumber.append("2");
where[0] = phoneNumber.toString();
This is much better method to build your string and store it into your 'where' array.
It's also possible to pre-allocate large enough memory size. Here is a simple stack implementation: the program is supposed to output 3 and 5.
class Stk {
static public final int STKSIZ = 256;
public int[] info = new int[STKSIZ];
public int sp = 0; // stack pointer
public void push(int value) {
info[sp++] = value;
}
}
class App {
public static void main(String[] args) {
Stk stk = new Stk();
stk.push(3);
stk.push(5);
System.out.println(stk.info[0]);
System.out.println(stk.info[1]);
}
}
I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size. You have to use an ArrayList or a Vector or any other dynamic structure.
Use a List<String>
, such as an ArrayList<String>
. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).
import java.util.*;
//....
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
System.out.println(list); // prints "[1, 2, 3]"
If you insist on using arrays, you can use java.util.Arrays.copyOf
to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.
static <T> T[] append(T[] arr, T element) {
final int N = arr.length;
arr = Arrays.copyOf(arr, N + 1);
arr[N] = element;
return arr;
}
String[] arr = { "1", "2", "3" };
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
arr = append(arr, "4");
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"
This is O(N)
per append
. ArrayList
, on the other hand, has O(1)
amortized cost per operation.
There is no method append()
on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.
List<String> where = new ArrayList<String>();
where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
Or if you are really keen to use an array:
String[] where = new String[]{
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
};
but then this is a fixed size and no elements can be added.
Apache Commons Lang has
T[] t = ArrayUtils.add( initialArray, newitem );
it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.
As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.
String[] where = new String[10];
This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a dynamically growing collection, use the ArrayList.
Adding new items to String array.
String[] myArray = new String[] {"x", "y"};
// Convert array to list
List<String> listFromArray = Arrays.asList(myArray);
// Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
List<String> tempList = new ArrayList<String>(listFromArray);
tempList.add("z");
//Convert list back to array
String[] tempArray = new String[tempList.size()];
myArray = tempList.toArray(tempArray);
If one really want to resize an array you could do something like this:
String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr));
// Output is: [a, b, c]
arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";
System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]
You can simply do this:
System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);
String[] source = new String[] { "a", "b", "c", "d" };
String[] destination = new String[source.length + 2];
destination[0] = "/bin/sh";
destination[1] = "-c";
System.arraycopy(source, 0, destination, 2, source.length);
for (String parts : destination) {
System.out.println(parts);
}
You need to use a Collection List. You cannot re-dimension an array.
Source: Stackoverflow.com