儘管String實現了CharSequence,但Java不允許這樣做。這個設計決定的原因是什麼?爲什麼我不能將HashMap <CharSequence,CharSequence>設置爲HashMap <String,String>
4
A
回答
6
來禁止該決定是因爲它不是類型安全:
public class MyEvilCharSequence implements CharSequence
{
// Code here
}
HashMap<CharSequence, CharSequence> map = new HashMap<String, String>();
map.put(new MyEvilCharSequence(), new MyEvilCharSequence());
現在我試圖把MyEvilCharSequence
成String
地圖。大問題,因爲MyEvilCharSequence
最肯定是而不是 a String
。
但是,如果你說:
HashMap<? extends CharSequence, ? extends CharSequence> map = new HashMap<String, String>();
那麼這樣的作品,因爲編譯器會阻止您添加非null
項目到地圖。這條線會產生一個編譯時錯誤:
// Won't compile with the "? extends" map.
map.put(new MyEvilCharSequence(), new MyEvilCharSequence());
See here對通用通配符的更多細節。
2
應該HashMap<? extends CharSequence, ? extends CharSequence>
相關問題
- 1. 爲什麼HashMap <String,Object>不接受HashMap <String,List>實例?
- 2. 爲什麼我們必須將HashMap <String,Object>轉換爲HashMap <String,Object> .toMap
- 3. Javapoet - TypeName - HashMap <String,HashMap <String,List <String> >> generation?
- 4. Map <String,Map <String,Boolean >> myMap = new HashMap <String,HashMap <String,Boolean >>();
- 5. 如何將HashMap <String,Integer> param轉換爲Map <String,Object)
- 6. Android將ArrayList <HashMap <String,String >> mylist轉換爲stringarray
- 7. 如何將List <NameValuePair>轉換爲hashMap <String,String>?
- 8. 爲什麼地圖<String, int> list = new HashMap <String, int>不允許?
- 9. 的Java設置<String>一個HashMap
- 10. 在ArrayAdapter中設置ArrayList <HashMap <String,String >>
- 11. 如何在AlertDialog中設置ArrayList <HashMap <String,String >>?
- 12. XStream with HashMap <String,String>
- 13. 加載數據到HashMap <String,HashMap <String,HashMap <String,ArrayList <ClassOb> >>>
- 14. 迭代HashMap <String,HashMap <String,Integer >>
- 15. 從ArrayList中獲取元素<HashMap <String,HashMap <String,String >>>
- 16. Android ArrayList <HashMap <String,String >>
- 17. 將ArrayList <HashMap <String,String >>附加到另一個ArrayList <HashMap <String,String >>
- 18. 將HashMap <String,String>綁定到MutableTreeNode
- 19. 構造函數ArrayAdapter <ArrayList <HashMap <String,String >>>(Context,int,ArrayList <HashMap <String,String >>)未定義
- 20. HashMap <String,String> temp = new HashMap <String,String>();對於通圖像
- 21. 如何正確聯合HashMap <String,ArrayList <Object>>和HashMap <String,Object>
- 22. Java:如何將HashMap <String,HashMap <Integer,ArrayList <Integer> >>寫入文件?
- 23. Proguard和HashMap <String,MyObject>
- 24. JSP訪問中的HashMap <HashMap <Integer,Integer>,String>
- 25. HashMap <String,ArrayList <Objects>>
- 26. set ArrayList <HashMap <String,Object>> value
- 27. 遍歷HashMap <String,List <Class>>
- 28. 如何將Json字符串轉換爲List <HashMap <String,String >>?
- 29. 如何將HashMap <String,列表<String[]>>轉換爲GWT中的Tree?
- 30. 如何將List <HashMap <String,String >>保存到SQLite db
http://stackoverflow.com/questions/7098402/implementations-and-collections/7098461#7098461的 –
可能重複[任何簡單的方式來解釋爲什麼我不能做列表動物=新的ArrayList ()?( http://stackoverflow.com/questions/2346763/any-simple-way-to-explain-why-i-cannot-do-listanimal-animals-new-arraylistdo) –