故事背景:
操作讀卡模塊,返回?cái)?shù)據(jù)是讀到的所有標(biāo)簽的ID,我是將所有ID放在一個(gè)List里面的。然后在讀卡器返回?cái)?shù)據(jù)時(shí),我更新RecyclerView的數(shù)據(jù)。
第一次我將RecyclerView的Adapter的數(shù)據(jù)集合mTagIDs=data(都是List<String>),這是相當(dāng)糟糕了,這壓根就是將mTagIDs重新指向新的對(duì)象,根本不會(huì)更新RecyclerView的數(shù)據(jù)。
然后我就是用了Collections.copy(dest,src)這個(gè)方法,然后就IndexOutOfBoundsException,看一下這個(gè)方法的注釋
Copies all of the elements from one list into another. After the
operation, the index of each copied element in the destination list
will be identical to its index in the source list. The destination
list must be at least as long as the source list. If it is longer, the
remaining elements in the destination list are unaffected.
就是dest的長(zhǎng)度要大于src的長(zhǎng)度,不然就越界。可是我怎么知道dest和src誰(shuí)更長(zhǎng)啊。
解決方式:
所以我只好放棄這個(gè)方法,改用Collections.addAll(Collection<? super T> c, T... elements);而且將之前的方法返回?cái)?shù)據(jù)由List<String>改成了String[].
強(qiáng)勢(shì)粘貼代碼
沒碼可粘,創(chuàng)造條件也要粘
public static <T> boolean addAll(Collection<? super T> c, T... elements) {
boolean result = false;
for (T element : elements)
result |= c.add(element);
return result;
}