2017-04-20 1 views
0

기본적으로, 나는 ArrayList 제목 "recentContacts"가, 그리고 난 지금 목록 후, 최초의 인덱스에서 모든 항목을 대체 할 ArrayList을 얻으려고 노력 메신저 (10)최근 항목에 대한 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 # removeEldestEntry()에서. –

+0

그 간단한 논리를하는 사람이 필요합니까? –

+0

단순함은 주관적입니다. 우리 모두는 다른 기술 수준에 있습니다. :) –

답변

3

교체 될 다음 요소의 색인을 유지 관리해야합니다. ArrayList이 "가득 참"이되기 전에 실제로 해당 색인을 사용할 수 있습니다. [의 LinkedHashMap (https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html)로 사용

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

고마워요! 매력처럼 작동합니다. –

관련 문제