1

我有这段代码,它工作正常:

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"),
      };
   }
4

4 回答 4

5

中没有动态分配JavaLists都是为了这个目的。例如, 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); }
于 2013-03-11T20:03:42.583 回答
4

使用列表。这就是列表的用途:

List<News> news = new ArrayList<News>();
news.add(new News(...));
于 2013-03-11T20:01:44.847 回答
1

如果您主要在列表中间添加和删除对象(顺序很重要),最好使用 LinkedList。如果经常使用随机访问,ArrayList 会是更好的选择,在这种情况下,您可以在 O(1) 时间内将一个元素添加到末尾。请参阅http://en.wikiversity.org/wiki/Java_Collections_Overview

于 2013-03-11T20:14:19.370 回答
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"));
于 2013-03-11T20:12:06.973 回答