2015-08-08 105 views
1

這可能看起來很愚蠢和/或容易的問題,但我無法做到這一點。將元素添加到ArrayList或ArrayAdapter中的特定索引

我從數據庫(僅)獲取數據。我需要同時獲得element及其id。例如,

+----------------+ 
| id | username | 
+----------------+ 
| 1 | user1 | 
| 12 | user2 | 
| 103 | user3 | 
+----------------+ 

當我填充ArrayListArrayAdapter(或者別的東西),我想兩者idusername

我試着在ArrayList中使用add(int index, String object)方法,在ArrayAdapter中使用insert(String object, int index)方法。但是,這兩種方法都返回了我同樣的錯誤:

java.lang.IndexOutOfBoundsException: Invalid index 12, size is 1

我怎樣才能解決這個問題?

謝謝。

+0

你能張貼代碼? – Preethi

+0

我加了一個答案,還有別的? – Andrew

回答

1

您使用了不存在的12索引。如果你想要一個元素添加到了最後,你可以使用這個簽名:

objectOfArrayList.add(strigObject); // add an element to end 

而且,你必須經常檢查數組的大小:

int index = 16; 
if (objectOfArrayList.size() > index) { 
    objectOfArrayList.add(index -1, stringObject); // add an element to position 
} 

有進行檢查添加或插入值的ArrayList對象:

private void rangeCheckForAdd(int index) { 
    if (index > size || index < 0) 
     throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 
} 

UPDATE:

如果你需要一個結構 「key - value」(由Vitaliy Tsvayer提出的想法),您將使用地圖:

// id - user 
LinkedHashMap<Integer, String> map = new LinkedHashMap<>(); 
map.put(1, "user1"); 
map.put(12, "user2"); 
map.put(103, "user3"); 

答案在評論中質疑:

LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); 
map.put("user", 1); 
int id = map.get("user"); 
System.out.println("id = " + id); // "id = 1" 

最後一個例子中可能會出現java.lang.NullPointerException,如果密鑰不存在。

+0

謝謝。但是如果只有3條記錄,那麼它不會添加元素? 我試過了,但沒有解決我的問題。 對不起,延遲迴復... –

+0

@MirjalalTalishinski,對於這些目標使用'map' – Andrew

+0

@MirjalalTalishinski,我更新了 – Andrew

0

您得到的原因ArrayIndexOutOfBound的例外是您首先在索引1中插入1。 但直接試圖插入12。 但在當時列表的大小隻有1

我建議,可以用HashMap ..您存儲ID作爲密鑰和用戶名作爲值 即

Map<String, String> = new HashMap <String, String>(); 
map.put('1', "name 1"); 
相關問題