I have built a static method that adds an element to an array (which has a fixed size). You don't have to look at the entire method, it just creates a new array with a greater length and adds an element at the end of it, then returns the new array.
static int[] add(int[] oldArray, int value){
int n = oldArray.length;
int[] newArray = new int[n+1];
for(int i=0; i<n; i++){
newArray[i]=oldArray[i];
}
newArray[n] = value;
return newArray;
}
The method is supposed to be used as follows
int[] a = {2, 5};
a = add(a, 7);
Now the array a has three elements instead of two, namely 2, 5 and 7. The problem is, this is still a little messy. Is there a way to implement the method as non-static (in a "predefined array class" or something? I'm not too sure how to express it better) in such a way that it would work as follows instead?
int[] a = {2, 5};
a.add(7);
I'm trying to achieve this without using ArrayLists and NestedLists.
You cannot add a method to "the array class", same for all predefined classes, the only solution for other predefined classes is to inherit them and add the methods you want, but, this cannot be done for arrays as it has not a specific predefined class, it can be defined as a container object that holds a fixed number of values of a single type (Arrays).
The alternative solutions for what you want:
Use Lists (ArrayList for example), as described in the comments.
concatenate the array original content with the new element, for this solution, you can use ArrayUtils.addAll(T[] array1, T... array2) or System.arraycopy like the following sample (convert the new element to an array before)
String[] both = ArrayUtils.addAll(first, second);
Create a class to wrap the array (adding the array as a variable in this class), and create addElement method containing something like the following:
int[] newArray = new int[length + 1];
for (int i = 0; i < length; i++)
newArray[i] = this.array[i];
newArray[length] = element;
length ++;
array = newArray;
Is there a way to implement the method as non-static (in a "predefined array class" or something? I'm not too sure how to express it better) in such a way that it would work as follows instead?
No, there is not. You must use something like List, or optionally write your own interface that wraps an array (it cannot itself be an array).
What you're asking for are called "extension methods" in C#, but as others have already answered, they don't exist in Java. However, Project Lombok (which is full of very useful features that most professional Java developers should be aware of and use), implements them with a simple annotation.
Here's an example:
package so_75073262;
public class ArrayExtensions {
public static int[] add(int[] oldArray, int value) {
int n = oldArray.length;
int[] newArray = new int[n + 1];
for (int i = 0; i < n; i++) {
newArray[i] = oldArray[i];
}
newArray[n] = value;
return newArray;
}
}
package so_75073262;
import lombok.experimental.ExtensionMethod;
#ExtensionMethod(ArrayExtensions.class)
public class Usage {
public static void main(String[] args) {
int[] original = {2,5};
int[] modified = original.add(7);
System.out.println(modified[0]);
System.out.println(modified[1]);
System.out.println(modified[2]);
}
}
Lombok is a form of "magic" and probably would get "interesting" responses from some course instructors; I'm not sure I'd recommend using this in an introductory Java class. But it's still useful to know about; it's a powerful tool to have in your toolbox, and can help keep code tidy and uncluttered.
I think you should take a reference of How ArrayList is getting implemented and how its size increases dynamically. Since it uses Array internally for the implementation, you might get some suggestions from there.
Related
I need the simplest way to add an item to the front of an Java array.
I need the Java array NOT the ArrayList.
There are two ways to do this. One, using Objects or another using generics. I recommend you to use generics because gives you more flexibility as you gonna see in these examples.
In this first implementation the function add2BeginningOfArray is using generics:
public static <T> T[] add2BeginningOfArray(T[] elements, T element)
{
T[] newArray = Arrays.copyOf(elements, elements.length + 1);
newArray[0] = element;
System.arraycopy(elements, 0, newArray, 1, elements.length);
return newArray;
}
Calling this function is really simple. For instance, if you have a class Dot and you want to add an element to the beginning of an array of Dot objects you just need to do this:
int size = 20;
Dot[] dots = new Dot[size];
for (int i = 0; i < size; i++) {
dots[i] = new Dot("This is a dot");
}
Dot goal = new Dot("This is a goal");
System.out.println(Arrays.toString(add2BeginningOfArray(dots, goal)));
You can also implement a function declaring the function parameters as Object as shown in this example:
public static Object[] add2BeginningOfArray(Object[] elements, Object element){
Object[] tempArr = new Object[elements.length + 1];
tempArr[0] = element;
System.arraycopy(elements, 0, tempArr, 1, elements.length);
}
Now, what is the problem? Well, not a big problem but now you need to declare your array as Object[] and use this kind of declaration to work with it.
Object[] foo = {"2", "3", "4"};
//adding an element to the beginning array
Object[] numbers = add2BeginningOfArray(foo, "1");
System.out.println(Arrays.toString(numbers));
For me the generics approach is cleaner and more scalable, so I really recommend it over the Object approach.
Apache Commons Lang class 'ArrayUtils' makes this very easy, if that is an option for you:
char[] arrayA = {'b', 'c'};
char[] arrayB = ArrayUtils.add(arrayA, 0, 'a');
// arrayB: [a, b, c]
for(int i = roadVehicles.length; i > 0; i--) {
if (roadVehicles[i-1] != null) {
roadVehicles[i] = roadVehicles[i-1];
}
}
roadVehicles[0] = car;
As per the Java tutorials (which I thoroughly recommend beginners to work through)
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Because arrays cannot be resized - you can overwrite the first element, but to perform an insert you must create a new array 1 larger than the previous one, put your new element in the first position and fill the rest of the array with the existing elements.
Of course, in practice don't do this. Instead use a collection that suits your actual use-case.
So the actual answer to your question is: The simplest way to add an item to front of a java array is to use a better collection type such as a Deque.
I cannot think of any valid reason in Java to not use a more appropriate collection than a raw array if inserting to the front is required.
Once created an array cannot be resized. If you have to add an element you'll need to create a new array.
If you know the array type it's trivial, but a nicer solution will work with any array type, using the java.lang.reflect.Array
Example code:
public static Object addElementInFrontOfArray(Object array, Object element) {
int newArraySize = Array.getLength(array)+1;
Object newArray = Array.newInstance(element.getClass(), newArraySize);
//Add first element
Array.set(newArray, 0, element);
for (int i=1 ; i<newArraySize; i++) {
Array.set(newArray, i, Array.get(array, i-1));
}
return newArray;
}
Consider that you can pass a int[] array as parameter but a Integer[] arrary will be returned
Considering this source
https://www.journaldev.com/763/java-array-add-elements
you can add new elements at the beginning of you array by doing this:
public static Object[] add(Object[] arr, Object... elements){
Object[] tempArr = new Object[arr.length+elements.length];
System.arraycopy(arr, 0, tempArr, elements.length, arr.length);
for(int i=0; i < elements.length; i++)
tempArr[i] = elements[i];
return tempArr;
}
Why not just use an ArrayList?
You could use an Array convert it to a List as follows:
List<Integer> myList = Arrays.asList(1,2,3);
//Instead of 1,2,3 you could create an Integer array: Integer[] myArray = {1,2,3};
myList.add(0, 25);
If you decide doing this way, you could check the answers of this question:
Java Arrays how to add elements at the beginning
or just check out the documentation:
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
here's a concrete example of the simplest way I could find:
List<StackTraceElement> stack = new ArrayList<StackTraceElement> (Arrays.asList (e.getStackTrace()));
stack.add (0, new StackTraceElement ("class", "method", "file", 25439));
StackTraceElement[] newStack = new StackTraceElement[stack.size()];
newStack = stack.toArray (newStack);
e.setStackTrace (newStack);
Basically it uses java.util.Arrays.asList() to turn the array into a List, adds to the list and then turns the list back into an array with List.toArray().
As everybody has said, you can't really add to the beginning of an array unless you shift all the elements by one first, or as in my solution, you make a new array.
Just .unshift()
This adds an element to the beginning of an array.
I am trying to create an array of arrays of arrays etc..., except I don't know how many nested levels deep it needs to be until runtime.
Depending on the input, I might need either int[], int[][], int[][][][][][], or anything else. (For context, I am trying to construct an N-dimensional grid for a cellular automaton, where N is passed as a parameter.)
I don't have any code for you because I have no idea how to go about this; I suspect is not possible at all using just arrays. Any help, or alternative solutions, would be appreciated.
You could do this with an Object[], limiting its members to either Object[] or int[].
For example, here's an array that goes three levels deep in one part, and two levels deep in another:
Object[] myarray = new Object[] {
new Object[] { new int[] { 1, 2 },
new int[] { 3, 4 }},
new int[] { 5, 6 }
};
After you've created it, you may want to access members. In your case, you know the depth N up front, so you know at what depth to expect an Object[] and at what depth to expect an int[].
However, if you didn't know the depth, you could use reflection to determine whether a member is another Object[] level or a leaf int[].
if ( myarray[0] instanceof Object[] ) {
System.out.println("This should print true.");
}
EDIT:
Here's a sketch [untested so far, sorry] of a method that access a member of an array of known depth, given an array of indices. The m_root member can be an Object[] or an int[]. (You could relax this further to support scalars.)
public class Grid {
private int m_depth;
private Object m_root;
...
public int get( int ... indices ) {
assert( indices.length == m_depth );
Object level = m_root;
for ( int i = 0; i + 1 < m_depth; ++i ) {
level = ((Object[]) level)[ indices[i] ];
}
int[] row = (int[]) level;
return row[ indices[m_depth - 1] ];
}
}
This should be achievable using Object[], since arrays are objects:
int[] arr = {1,2,3};
int[] arr2 = {1,2,3};
int[] arr3 = {1,2,3};
int[] arr4 = {1,2,3};
Object[] arr5 = {arr, arr2}; // basically an int[][]
Object[] arr6 = {arr3, arr4}; // basically an int[][]
Object[] arr7 = {arr5, arr6}; // basically an int[][][]
// etc.
Note that one array doesn't have to contain arrays of the same dimensions:
Object[] arr7 = {arr5, arr};
To prevent this (and to allow for easier access to the data), I suggest writing a class which has an Object member (which will be your int[] or Object[]) and a depth variable and some nice functions to give you access to what you want.
ArrayLists will also work:
ArrayList array = new ArrayList();
array.add(new ArrayList());
array.add(new ArrayList());
((ArrayList)array.get(0)).add(new ArrayList());
// etc.
As your N increases going with nested arrays becomes less and less advantageous, especially when you have a grid structure. Memory usage goes up exponentially in N with this approach and the code becomes complex.
If your grid is sparsely populated (a lot of cells with the same value) you can instead have a collection of Cell objects where each of these holds a coordinate vector and the integer value of the cell. Every cell that is not in the collection is assumed to have a default value, which is your most common value.
For faster access you can use for example a k-d tree (https://en.wikipedia.org/wiki/K-d_tree) but that depends a bit on your actual use-case.
#Andy Thomas explains how to do this using Object[] for the higher levels of the multidimensional array. Unfortunately, this means that the types are not correct to allow indexing, or indeed to allow element access without typecasts.
You can't do this:
Object[] array = ...
int i = array[1][2][3][4];
To get types that allow you to do the above, you need to create an object whose real type is (for example) int[][][][].
But the flipside is that it is not really practical to use that style of indexing for N dimensional arrays where N is a variable. You can't write Java source code to do that unless you place a bound on N (i.e. up to 5) and treat the different cases individually. That becomes unmanageable very quickly.
You can use Java reflection as Arrays are objects.
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
Class<?> intClass = int.class;
Class<?> oneDimensionalArrayClass = Class.forName("[I");
Object oneDimensionalIntArray1 = Array.newInstance(intClass, 1);
Array.set(oneDimensionalIntArray1, 0, 1);
Object oneDimensionalIntArray2 = Array.newInstance(intClass, 1);
Array.set(oneDimensionalIntArray2, 0, 2);
Object oneDimensionalIntArray3 = Array.newInstance(intClass, 1);
Array.set(oneDimensionalIntArray3, 0, 3);
Object twoDimensionalIntArray = Array.newInstance(oneDimensionalArrayClass, 3);
Array.set(twoDimensionalIntArray, 0, oneDimensionalIntArray1);
Array.set(twoDimensionalIntArray, 1, oneDimensionalIntArray2);
Array.set(twoDimensionalIntArray, 2, oneDimensionalIntArray1);
System.out.println(Array.get(Array.get(twoDimensionalIntArray, 1), 0));
}
The class Array with its static methods gives access on items while you can specify the dimension of your arrays with the number of leading "[".
The whole construct of multi-dimensional arrays is just the compiler doing some work for you on a big block of memory (ok as some have commented in java this is multiple blocks of memory). One way to deal with the problem you face is to use nested arraylists at runtime. Another (more performant) way is to just allocate a single-dimensional array of the size you need and do the indexing yourself. You could then hide the indexing code in a method that was passed all the details like an array de-reference.
private int[] doAllocate(int[] dimensions)
{
int totalElements = dimensions[0];
for (int i=1; i< dimensions.length; i++)
{
totalElements *= dimensions[i];
}
int bigOne = new int[totalElements];
return bigOne;
}
private int deReference(int[] dimensions, int[] indicies, int[] bigOne)
{
int index = 0;
// Not sure if this is only valid when the dimensions are all the same.
for (int i=0; i<dimensions.length; i++)
{
index += Math.pow(dimensions[i],i) * indicies[dimensions.length - (i + 1)];
}
return bigOne[index];
}
Fields like you wrote above a checked and created by the compiler. If you want a dynamic data structure during runtime you could create your own data structure. Search for Composite Pattern. A small snippet should show you how it works:
interface IGrid {
void insert(IGrid subgrid);
void insert(int[] values);
}
class Grid implements IGrid {
private IGrid subgrid;
void insert(IGrid subgrid) {this.subgrid = subgrid;}
void insert(int[] values) {/* Do nothing */}
}
class SubGrid implements IGrid {
private int[] values;
void insert(IGrid subgrid) {/* Do nothing */}
void insert(int[] values) {this.values = values;}
}
You could simply create a Subgrid for int[] or a Grid with a Subgrid for int[][]. It's only a rudimental solution, you would have to create some code for working on your automaton's levels and values. I would do it this way. Hope it will help :) And look forward for more solutions^^
All I need is the simplest method of sorting an ArrayList that does not use the in-built Java sorter. Currently I change my ArrayList to an Array and use a liner sorting code, but I later need to call on some elements and ArrayLists are easier to do that.
you can use anonymous sort.
Collections.sort(<ArrayList name>, Comparator<T>() {
public int compare(T o1, T o2) {
.....
....
}
});
where T is the type you want to sort (i.e String, Objects)
and simply implement the Comparator interface to your own needs
Assuming an ArrayList<String> a...
Easiest (but I'm guessing this is what you're saying you can't use):
Collections.sort(a);
Next easiest (but a waste):
a = new ArrayList<String>(new TreeSet<String>(a));
Assuming "in-built sort" refers to Collections.sort() and you are fine with the sorting algorithm you have implemented, you can just convert your sorted array into an ArrayList
ArrayList list = new ArrayList(Arrays.asList(sortedArray));
Alternatively, you can rewrite your sorting algorithm to work with a List (such as an ArrayList) instead of an array by using the get(int index) and set(int index, E element) methods.
Sorting Arguments passed through Command prompt; without using Arrays.sort
public class Sort {
public static void main(String args[])
{
for(int j = 0; j < args.length; j++)
{
for(int i = j + 1; i < args.length; i++)
{
if(args[i].compareTo(args[j]) < 0)
{
String t = args[j];
args[j] = args[i];
args[i] = t;
}
}
System.out.println(args[j]);
}
}
}
By using Array.sort
import java.util.*;
public class IntegerArray {
public static void main(String args[])
{
int[] num=new int[]{10, 15, 20, 25, 12, 14};
Arrays.sort(num);
System.out.println("Ascending order: ");
for (int i=0; i<num.length; i++)
System.out.print(num[i] + " ");
}
}
Collections.sort(List);
If i remember correctly when you pull an element out of the middle of an arrayList it moves the rest of the elements down automaticly. If you do a loop that looks for the lowest value and pull it out then place it at the end of the arrayList. On each pass i-- for the index. That is use one less. So on a 10 element list you will look at all 10 elements take the lowest one and append it to the end. Then you will look at the first nine and take the lowest of it out and append it to the end. Then the first 8 and so on till the list is sorted.
Check for Comparator in java. You can implement your own sorting using this and use Collections.sort(..) to sort the arraylist using your own Comparator
If you are meant to sort the array yourself, then one of the simplest algorithms is bubble sort. This works by making multiple passes through the array, comparing adjacent pairs of elements, and swapping them if the left one is larger than the right one.
Since this is homework, I'll leave it to you to figure out the rest. Start by visualizing your algorithm, then think about how many passes your algorithm needs to make, and where it needs to start each pass. Then code it.
You also need to understand and solve the problem of how you compare a pair of array elements:
If the elements are instances of a primitive type, you just use a relational operator.
If the elements are instances of reference types, you'll need to use either the Comparable or Comparator interface. Look them up in the javadocs. (And looking them up is part of your homework ...)
Here is a "simple" quicksort implementation:
public Comparable<Object>[] quickSort(Comparable<Object>[] array) {
if (array.length <= 1) {
return array;
}
List<Comparable<Object>> less = new ArrayList<Comparable<Object>>();
List<Comparable<Object>> greater = new ArrayList<Comparable<Object>>();
Comparable<Object> pivot = array[array.length / 2];
for (int i = 0;i < array.length;i++) {
if (array[i].equals(pivot)) {
continue;
}
if (array[i].compareTo(pivot) <= 0) {
less.add(array[i]);
} else {
greater.add(array[i]);
}
}
List<Comparable<Object>> result = new ArrayList<Comparable<Object>>(array.length);
result.addAll(Arrays.asList(quickSort(less.toArray(new Comparable<Object>[less.size()]))));
result.add(pivot);
result.addAll(Arrays.asList(quickSort(greater.toArray(new Comparable<Object>[greater.size()]))));
return result.toArray(new Comparable<Object>[result.size()]);
}
The last operations with arrays and list to build the result can be enhanced using System.arraycopy.
In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}
I am trying to add, remove and reference items from an array I create in my main java file, but I am having trouble figuring out the correct syntax. In actionscript they have push() and pop() for adding and removing items in an array, is there an equivalent in android?
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.
For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, 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;
}
Use Array list
http://developer.android.com/reference/java/util/ArrayList.html
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
You can use LinkedList. It has methods peek, poll and offer.