Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to add an element to Array specifying position and value. For example, I have Array

int []a = {1, 2, 3, 4, 5, 6};

after applying addPos(int 4, int 87) it should be

int []a = {1, 2, 3, 4, 87, 5};

I understand that here should be a shift of Array's indexes, but don't see how to implement it in code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

This should do the trick:

public static int[] addPos(int[] a, int pos, int num) {
    int[] result = new int[a.length];
    for(int i = 0; i < pos; i++)
        result[i] = a[i];
    result[pos] = num;
    for(int i = pos + 1; i < a.length; i++)
        result[i] = a[i - 1];
    return result;
}

Where a is the original array, pos is the position of insertion, and num is the number to be inserted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...