本文介绍了以特定间隔将项目添加到arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试每隔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个元素为new.
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));
}
这篇关于以特定间隔将项目添加到arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!