mr_ecko
mr_ecko

Reputation: 61

How can i place an element in an array on a given position?

I have the following question.

int[] ar={4,6,7,8}

Now i want to add an element so i get

ar={4,6,9,7,8}

I want to be able to add a given element (9) in a position that i want i this case index 2. How?

Upvotes: 0

Views: 354

Answers (4)

deezy
deezy

Reputation: 1480

In Java, the size of an array cannot be changed. Instead you can use a List:

List<Integer> numList = new ArrayList<Integer>();
numList.add(4);
numList.add(6);
numList.add(7);
numList.add(8);

Then you can use numList.add(int index, E element); to insert values at specific positions.

numList.add(2, 9);
//numList = {4, 6, 9, 7, 8};

For further information you may want to look at this tutorial.

Upvotes: 3

Josh Stevens
Josh Stevens

Reputation: 4221

The most simple way of doing this is to use an ArrayList<Integer> and use the add(int, T) method.

List<Integer> numList = new ArrayList<Integer>();
numList.add(4);
numList.add(6);

// Now, we will insert the number
numList.add(2, 9);

Upvotes: 0

mjalkio
mjalkio

Reputation: 78

How to add new elements to an array?

add an element to int [] array in java

Note that ArrayList also has an add method that lets you specify an index and the element to be added void add(int index, E element).

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

Java arrays are fixed length, so you'll need to create another one to store your extra element.

int[] ar = { 4, 6, 7, 8 };
int[] tmp = new int[ar.length + 1];
int pos = 2;
for (int i = 0; i < pos; i++) {
    tmp[i] = ar[i];
}
for (int i = pos + 1; i <= ar.length; i++) {
    tmp[i] = ar[i - 1];
}
tmp[pos] = 9;
System.out.println(Arrays.toString(tmp));

Output is (as requested)

[4, 6, 9, 7, 8]

Upvotes: 0

Related Questions