10

I need the simplest way to add an item to the front of an Java array.
I need the Java array NOT the ArrayList.

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Eminem
  • 7,206
  • 15
  • 53
  • 95

10 Answers10

8

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.

Teocci
  • 7,189
  • 1
  • 50
  • 48
6

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]
Manuel
  • 649
  • 8
  • 13
3
for(int i = roadVehicles.length; i > 0; i--) {
    if (roadVehicles[i-1] != null) {
        roadVehicles[i] = roadVehicles[i-1];                
    }
}
roadVehicles[0] = car;
Eminem
  • 7,206
  • 15
  • 53
  • 95
  • 3
    Please explain what your code is actually doing (I don't thinks that this correctly answers the _unclear_ question or is only one solution to alt least two) – try-catch-finally Apr 23 '16 at 12:01
2

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.

Matt Coubrough
  • 3,739
  • 2
  • 26
  • 40
  • Unfortunately its a requirement. I basically need to shift items 'down' when inserting items at the front – Eminem Apr 23 '16 at 07:28
  • 2
    If it is a requirement - then find another employer! Programming is hard enough without having to met absurd arbitrary restrictions. If it is for an assignment or educational purposes then creating a new array 1 larger is the *simplest* solution, but certainly not the most efficient. – Matt Coubrough Apr 23 '16 at 07:40
  • @Eminem, sounds like you just answered your own question then. – ChiefTwoPencils Apr 23 '16 at 07:40
  • @MattCoubrough Here's a valid reason: `Throwable.getStackTrace()` returns an array of `StackTraceElement`. You might want to catch that exception, add the trace element for the method that caught it to the beginning of that array, and then put it back in the exception with `setStackTrace (StackTraceElement[])`. – PMorganCA Mar 21 '19 at 18:57
2

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

2

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;

}
1

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

Community
  • 1
  • 1
Carlos Parra
  • 957
  • 9
  • 19
  • Because I was asked NOT to use an arraylist – Eminem Apr 23 '16 at 07:27
  • Well, I think one way you could do that is creating another array with size: oldArray+elementsToInsert, so that you could add the new elements at the front and the others at the end. – Carlos Parra Apr 23 '16 at 07:35
  • Have you tried out your code? The ArrayList used by the Arrays::asList method doesn't override the default implementation of AbstractList::add(int, T) and therefore automatically throws an UnimplementedException. – Vincent Engel Sep 20 '19 at 13:49
  • Arrays.asList generates an immutable list, which means you can't add an element at the beginning. This is not valid code. – Sam Jul 05 '23 at 13:57
0

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.

PMorganCA
  • 730
  • 6
  • 24
0

I used this method:

public void addFront(Item item) { //add item to the front
    Item temp = arr[0];
    arr[0] = item;
    for (int i = 1; i < arr.length - 1; i++) {
        Item temp2 = arr[i];
        arr[i] = temp;
        temp = temp2;
    }
}

Still you shoud manage resising or ArrayIndexOutOfBoundsException in case you add more elements than initially predifined length of your array. It was exercise 3.5.27 from "Algorithms" fourth edition from Robert Sedgewick & Kevin Wayne.

Roman Lototskyi
  • 692
  • 1
  • 5
  • 13
-1

Just .unshift()

This adds an element to the beginning of an array.

Lukas
  • 11