Java 向数组中动态添加对象

Java 向数组中动态添加对象,java,arrays,list,oop,dynamic-allocation,Java,Arrays,List,Oop,Dynamic Allocation,我有这个代码,它工作得很好: 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[] = 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"),
      };
   }
使用一个。这就是列表的用途:

List<News> news = new ArrayList<News>();
news.add(new News(...));
使用一个。这就是列表的用途:

List<News> news = new ArrayList<News>();
news.add(new News(...));

Java中没有动态分配,我们在这里就是为了这个目的。 例如,列表、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);

Java中没有动态分配,我们在这里就是为了这个目的。 例如,列表、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);
但更好的方法是使用用户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"));
但更好的方法是使用用户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"));

如果你在列表顺序中间添加和删除对象是很重要的,最好使用链接列表。如果经常使用随机访问,ArrayList将是一个更好的选择,在这种情况下,您可以在O1时间内将一个元素添加到末尾。请参阅

> P>如果在列表顺序中间添加和删除对象是很重要的,最好使用Link键列表。如果经常使用随机访问,ArrayList将是一个更好的选择,在这种情况下,您可以在O1时间内将一个元素添加到末尾。看