以特定间隔将项目添加到数组列表 [英] Add item to arraylist at specific interval

查看:20
本文介绍了以特定间隔将项目添加到数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在每 4 个项目之后向 ArrayList 添加一个元素.

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

ArrayList 应该是这样的,

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

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

所以我使用代码

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?

推荐答案

为了使其更具可读性,您还可以尝试使用新的 ArrayList.循环遍历现有的数组列表并将元素添加到新的 ArrayList 中,条件是每 4 个元素都是新的.

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

这篇关于以特定间隔将项目添加到数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆