[問題] Serializable 轉型的問題

看板java作者 (PTT新聞)時間13年前 (2012/11/28 14:47), 編輯推噓4(401)
留言5則, 3人參與, 最新討論串1/2 (看更多)
class obj implements Serializable { public String str = "abcdefg"; } public class TestConverType { public void ConverType(Map<String,Object> in) { } public static void main(String[] args) { obj o1 = new obj(); TestConverType ct = new TestConverType(); Map<String, Serializable> t1 = new HashMap<String,Serializable>(); t1.put("o1", o1); ct.ConverType(t1); } } 我本來想把 t1 直接當參數,傳給ConverType 可是會出現 錯誤訊息 The method ConverType(Map<String,Object>) in the type TestConverType is not applicable for the arguments (Map<String,Serializable>) 必須透過轉型 ct.ConverType(new HashMap<String,Object>(t1)) 請問 1. Object 不是萬物根源嗎? ,為何不能接受Serializable 2. 透過轉型的物件,會不會比較吃記憶體? 謝謝~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.120.175.188

11/28 15:04, , 1F
這不是轉型問題,是泛型問題,你的需求可以加上wildcard來解
11/28 15:04, 1F
這招我會,順道提出說明 TestConverType.ConverType() 及 obj 程式內容都不能修改 因為一個是第三方Lib , 一個是別人寫的複雜Code 兩邊我都不想動。 ※ 編輯: pttnews 來自: 59.120.175.188 (11/28 15:16)

11/28 15:17, , 2F
這是轉型問題 Serializable是介面 不繼承Object
11/28 15:17, 2F
所以 Object 不是萬物根源, 眼中容不下 interface ※ 編輯: pttnews 來自: 59.120.175.188 (11/28 15:25)

11/28 15:43, , 3F
沒錯.... Object跟interface是兩種不同的東西....
11/28 15:43, 3F

11/28 16:05, , 4F
啊不對我錯了 這是泛型問題不是轉型問題 泛型不會因為繼承
11/28 16:05, 4F

11/28 16:07, , 5F
就接受
11/28 16:07, 5F
文章代碼(AID): #1GjRE1Ws (java)
文章代碼(AID): #1GjRE1Ws (java)