문제

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"),
      };
   }
도움이 되었습니까?

해결책

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

다른 팁

Use a List. That's what Lists are for:

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

If you are mostly adding and removing objects in the middle of the list (order is important), it is better to use LinkedList. If random access is frequently used, ArrayList would be a better choice, in this case you can add an element to the end in O(1) time. See http://en.wikiversity.org/wiki/Java_Collections_Overview

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

but a better approach would be to user ArrayList. They are made for dynamic Structures.

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"));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top