Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

java - Add item to arraylist at specific interval

I am trying to add an element to ArrayList after every 4 items.

ArrayList after this should be like,

item|item|item|item|new_item|item|item|item|item|new_item|item...

So I use the code

int x=0;
for (int i=1;i<myNews.size();i++) {           
    if (i%4==0) {
        NewsData news = new NewsData();
        news.setId(999);
        news.setItem_type(3);
        news.setCat_id(97);
        myNews.add(i+x,news);
        x++;
    }
}

This doesn't seem to work as required. How would I achieve this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To make it more readable, you can also try using a new ArrayList. Loop through an existing array list and add elements to new ArrayList with an condition of every 4th element is new.

    List<NewsData> myNews = new ArrayList<>();
    List<NewsData> newNews = new ArrayList<>();

    for (int i = 0; i < myNews.size(); i++) {
        if (i % 4 == 0) {
            NewsData news = new NewsData();
            news.setId(999);
            news.setItem_type(3);
            news.setCat_id(97);
            myNews.add(news);
        }
        newNews.add(myNews.get(i));
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...