Search code examples
javaarrayslistoopdynamic-allocation

Dynamically add objects to array


I have this code and it works fine:

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

In this code I add 3 new objects but I have to add them dynamically inside a loop. How can I do this? I don't understand this array structure in fact. Please explain this code to me, if you can make it simple

I tried this but it does not works:

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

Solution

  • There is no dynamic allocation in Java, Lists are here on this purpose. For example, List, ArrayList, LinkedList...

    Used this way :

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

    And if you already have an array of News (in your example news_data), you can quickly fill your list to begin :

    for(News n : news_data) { list.add(n); }