我有这个代码,它工作正常:
News news_data[] = new News[] {
new News("1","news 1","this is news 1"),
new News("2","news 2","this is news 2"),
new News("2","news 1","this is news 2"),
};
在这段代码中我添加了3个新对象,但我必须在循环中动态添加它们。我怎样才能做到这一点?我实际上并不了解这个数组结构。如果你能简单的话,请向我解释一下这段代码
我尝试了这个,但它不起作用:
News news_data[];
for(i=1;i<3;i++){
news_data=new News[] {
new News("1","news 1","this is news 1"),
new News("2","news 2","this is news 2"),
new News("2","news 1","this is news 2"),
};
}
答案 0 :(得分:5)
Java
中没有动态分配,Lists
就是出于此目的。
例如,List
,ArrayList
,LinkedList
...
以这种方式使用:
// Declaring, initializing the list
ArrayList<News> list = new ArrayList<News>();
// Adding a news :
News news = new News("1","news 1","this is news 1");
list.add(news);
如果您已经有News
数组(在您的示例news_data
中),则可以快速填写列表以开始:
for(News n : news_data) { list.add(n); }
答案 1 :(得分:4)
使用List。这就是列表的用途:
List<News> news = new ArrayList<News>();
news.add(new News(...));
答案 2 :(得分:1)
如果您主要在列表中间添加和删除对象(顺序很重要),最好使用LinkedList。如果经常使用随机访问,则ArrayList是更好的选择,在这种情况下,您可以在O(1)时间内向末尾添加元素。见http://en.wikiversity.org/wiki/Java_Collections_Overview
答案 3 :(得分:0)
News news_data[] = new News[3]; // defining the size of Array to 3
new_data[0] = new News("1","news 1","this is news 1"),
new_data[1] = new News("2","news 2","this is news 2"),
new_data[2] = new News("2","news 1","this is news 2"),
但更好的方法是用户ArrayList。它们是为动态结构而制作的。
List<news> news_data = new ArrayList<News>();
news_data.add(new News("1","news 1","this is news 1"));
news_data.add(new News("2","news 2","this is news 2"));
news_data.add(new News("2","news 1","this is news 2"));