2017-04-20 70 views
0

基本上,我有一個ArrayList題爲「recentContacts」,和我有限的條目數10最近條目的ArrayList邏輯?

現在即時通訊試圖讓ArrayList從第一指數更換所有條目,名單後已滿。

下面是一些代碼來演示...

  // Limits number of entries to 10 
      if (recentContacts.size() < 10) 
      { 
       // Adds the model 
       recentContacts.add(contactsModel); 
      } 
      else 
      { 
       // Replaces model from the 1st index and then 2nd and 3rd etc... 
       // Until the entries reach the limit of 10 again... 
       // Repeats 
      } 

注:如果上述說法只是一個簡單的例子,可能不是解決問題的正確方法。

什麼將是實現這一目標的最簡單的方法是什麼?謝謝!

+0

考慮使用[LinkedHashMap的](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html),特別是外表在'LinkedHashMap#removeEldestEntry()'。 –

+0

你需要有人爲你做這個簡單的邏輯嗎? –

+0

簡單是主觀的。我們都在不同的技能水平。 :) –

回答

3

你必須保持將被替換的下一個元素的索引。 其實你可以使用該索引甚至在ArrayList是「全」。

例如:

int index = 0; // initialize the index to 0 when the ArrayList is empty 
... 
recentContacts.add(index,contactsModel); 
index = (index + 1) % 10; // once index reaches 9, it will go back to 0 
... 
+0

謝謝!奇蹟般有效。 –