简体   繁体   中英

Simplest way to add an item between items in a List


What is the simplest way to add an item between all items in a List?

For example, a List of Strings

{"1", "2", "3"}

becomes

{"1", ",", "2", "," "3"}


Edit 1
My first naive attempt which crashed and burned HARD (don't do this):

    for (int i=0; i < list.size(); i++) {
        if(i==0) continue;
        if(i==list.size()) continue;
        list.add(i, new String(","));
    }

You have a very functional way to think about your problem. Here is what I would do:

// use ArrayList, it is very easy to handle and comes with all necessary methods as Payam already said
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");

// this is the actual solution:
for (int i = 1; i < list.size(); i += 2) {
    list.add(i, ",");
}

// and this is just for testing (printing) the list
for (String s : list) {
    System.out.print("'"+s + "' ");
}

Expected outcome would be:

'1' ',' '2' ',' '3'

So, you loop through your list.
First: your index i starts at 1 (you don't want to add anything before the first element).

Then instead of incrementing your index by one ( i++ ) you increment it by two ( i+=2 ). That way your index points to every even position in the list.

At last you want to use add(index, value) to add a new value (here: , ) to the list at the specified position. Adding a new value to position any position will shift the following elements of your list "one to the left". They will not be overwritten (only moved to another index) and you can still loop your list from the beginning to the end, since you don't care if it grows in size or not.

Why don't you just use an ArrayList it's way easier to add and remove items.

Adding:

ArrayList<Integer> arrlist = null;
arrlist.add(0, 2);
....

Removing:

arrlist.remove(index);

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