2013-03-11 145 views
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"), 
     }; 
    } 

回答

5

有一個在Java沒有動態分配,Lists在這裏這樣的目的。 例如,ListArrayListLinkedList ...

這樣使用:

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

使用List。這就是解釋是:

List<News> news = new ArrayList<News>(); 
news.add(new News(...)); 
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"), 

,但更好的方法將b e傳給用戶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")); 
1

如果您主要在列表中間添加和刪除對象(順序很重要),最好使用LinkedList。如果經常使用隨機訪問,ArrayList將是更好的選擇,在這種情況下,您可以在O(1)時間內將元素添加到末尾。見http://en.wikiversity.org/wiki/Java_Collections_Overview