您好,登錄后才能下訂單哦!
這篇文章主要介紹“Java之HashMap.values()轉(zhuǎn)List時錯誤怎么解決”,在日常操作中,相信很多人在Java之HashMap.values()轉(zhuǎn)List時錯誤怎么解決問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Java之HashMap.values()轉(zhuǎn)List時錯誤怎么解決”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
因為項目中需要獲取到Map的值的集合,所以調(diào)用了HashMap.values()方法轉(zhuǎn)成List,當(dāng)時是使用了以下代碼。
(邏輯上這樣想應(yīng)該沒問題,但生活總是會是不是給你一點小“”驚喜“”)
List<AreaItemOpt> areaItemOpts = (List<AreaItemOpt>) areaItemOptMap.values(); return areaItemOpts;
懷著喜悅的心情在測試環(huán)境中運行之后,它報錯了!
報錯如下:
java.lang.ClassCastException: java.util.HashMap$Values cannot be cast to java.util.List
于是翻了一下values()方法的源碼
public Collection<V> values() { Collection<V> vs = values; return (vs != null ? vs : (values = new Values())); }
原來values()方法只是返回了一個Collection集合,可是如程序中的用法所示,在向下轉(zhuǎn)型的時候出現(xiàn)了類型轉(zhuǎn)換錯誤。
在ArrayList中,有一個構(gòu)造函數(shù)
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
可以接受一個集合類型的參數(shù),然后返回一個list;這樣就達到了預(yù)期目的。
代碼如下:
List<AreaItemOpt> areaItemOpts = new ArrayList<>(areaItemOptMap.values()); return areaItemOpts;
測試通過~
發(fā)現(xiàn)還有一種方法也可以解決這個問題:
List<T> list=(List<T>) Arrays.asList(map.values().toArray());//先轉(zhuǎn)數(shù)組再轉(zhuǎn)list
不多廢話,直接看代碼,有注解
public class Map轉(zhuǎn)List { public static void main(String[] args) { //開辟空間 HashMap<Integer,String> hashMap = new HashMap<Integer,String>(); //存入數(shù)據(jù) hashMap.put(1,"張三"); hashMap.put(2,"李四"); hashMap.put(3,"王五"); //使用Collection類型接收HashMap的Value值 Collection<String> collection = hashMap.values(); //把Collection對象作為參數(shù)傳入ArrayList構(gòu)造方法完成類型轉(zhuǎn)換 ArrayList<String> arrayList = new ArrayList<String>(collection); //輸出測試 System.out.println(arrayList.toString()); } }
到此,關(guān)于“Java之HashMap.values()轉(zhuǎn)List時錯誤怎么解決”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。