看板 java 關於我們 聯絡資訊
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
No:這不是轉型問題,是泛型問題,你的需求可以加上wildcard來解 11/28 15:04
這招我會,順道提出說明 TestConverType.ConverType() 及 obj 程式內容都不能修改 因為一個是第三方Lib , 一個是別人寫的複雜Code 兩邊我都不想動。 ※ 編輯: pttnews 來自: 59.120.175.188 (11/28 15:16)
pzyc79:這是轉型問題 Serializable是介面 不繼承Object 11/28 15:17
所以 Object 不是萬物根源, 眼中容不下 interface ※ 編輯: pttnews 來自: 59.120.175.188 (11/28 15:25)
LaPass:沒錯.... Object跟interface是兩種不同的東西.... 11/28 15:43
pzyc79:啊不對我錯了 這是泛型問題不是轉型問題 泛型不會因為繼承 11/28 16:05
pzyc79:就接受 11/28 16:07