简体   繁体   中英

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?

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 .

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]

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) .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM