equivalent to push() or pop() for arrays?
Solution 1:
In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.
int[] i = new int[10];
The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:
int[] i = new int[11];
In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.
Solution 2:
Use Array list http://developer.android.com/reference/java/util/ArrayList.html
Solution 3:
For those who don't have time to refactor the code to replace arrays with Collection
s (for example ArrayList
), there is an alternative. Unlike Collection
s, the length of an array cannot be changed, but the array can be replaced, like this:
array = push(array, item);
The drawbacks are that
- the whole array has to be copied each time you push, and
- the original array
Object
is not changed, so you have to update the variable(s) as appropriate.
Here is the push
method for String
:
(You can create multiple push
methods, one for String
, one for int
, etc)
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
for (int i = 0; i < array.length; i++)
longer[i] = array[i];
longer[array.length] = push;
return longer;
}
This alternative is more efficient, shorter & harder to read:
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
System.arraycopy(array, 0, longer, 0, array.length);
longer[array.length] = push;
return longer;
}
Solution 4:
You can use Arrays.copyOf()
with a little reflection to make a nice helper function.
public class ArrayHelper {
public static <T> T[] push(T[] arr, T item) {
T[] tmp = Arrays.copyOf(arr, arr.length + 1);
tmp[tmp.length - 1] = item;
return tmp;
}
public static <T> T[] pop(T[] arr) {
T[] tmp = Arrays.copyOf(arr, arr.length - 1);
return tmp;
}
}
Usage:
String[] items = new String[]{"a", "b", "c"};
items = ArrayHelper.push(items, "d");
items = ArrayHelper.push(items, "e");
items = ArrayHelper.pop(items);
Results
Original: a,b,c
Array after push calls: a,b,c,d,e
Array after pop call: a,b,c,d
Solution 5:
You can use LinkedList. It has methods peek, poll and offer.