2012-10-07 17 views
2

我有一個類,我試圖用來測試HashMap和TreeMap,如下所示;使用Java中的通用映射問題

public class TestMap<KeyType, ValueType> 
{ 
private Map<KeyType, ValueType> internalMap; 

/* 
* Entry point for the application 
*/ 
public static void main(String [ ] args) 
{ 
    TestMap<String, Integer> testHashMap = new TestMap<String,Integer>(new HashMap<String, Integer>()); 
    testHashMap.test(); 

    TestMap<String, Integer> testTreeMap = new TestMap<String,Integer>(new TreeMap<String, Integer>()); 
    testTreeMap.test(); 
}  

/* 
* Constructor which accepts a generic Map for testing 
*/ 
public TestMap(Map<KeyType, ValueType> m) 
{ 
    this.internalMap = m; 
} 

public void test() 
{ 
    try 
    { 
     //put some values into the Map 
     this.internalMap.put("Pittsburgh Steelers", 6); 

     this.printMap("Tested Map", this.internalMap); 
    } 
    catch (Exception ex) 
    { 

    } 
} 

}

在嘗試呼叫我收到下面的錯誤消息的put()方法;

的方法放(關鍵字類型,值類型)在類型地圖是不適用的參數(字符串,整數)

我沒有收到任何其他警告,我不明白爲什麼我得到這個?這不是泛型的全部點嗎?一般定義並具體實現?

感謝您的幫助!

+1

另外,泛型類型參數通常限制爲單個大寫字母,例如。 '公共課MyClass {'。通常使用「E」或「T」,對於地圖使用「K」和「V」。 – Dunes

回答

4

test()方法是TestMap類的一部分。在TestMap方法的任何一箇中,只能引用泛型類型,而不是任何特定的類型(因爲這取決於單個實例)。但是,您可以這樣做:

public static void main(String [ ] args) 
{ 
    TestMap<String, Integer> testHashMap = new TestMap<String,Integer>(new HashMap<String, Integer>()); 
    testHashMap.internalMap.put("Pittsburgh Steelers", 6); 

    TestMap<String, Integer> testTreeMap = new TestMap<String,Integer>(new TreeMap<String, Integer>()); 
    testTreeMap.internalMap.put("Pittsburgh Steelers", 6); 
} 
3

問題是您的整體類是通用的,但您試圖用一組特定類型對其進行測試。嘗試將測試方法移出對象並在TestMap<String, int>上使用它。

1

另一個選項是從您的TestMap對象中刪除泛型。他們目前似乎沒有做任何事情。

public class TestMap { 
    private Map<String, Integer> internalMap; 

    /* 
    * Entry point for the application 
    */ 
    public static void main(String [ ] args) 
    { 
     TestMap testHashMap = new TestMap(new HashMap<String, Integer>()); 
     testHashMap.test(); 

     TestMap testTreeMap = new TestMap(new TreeMap<String, Integer>()); 
     testTreeMap.test(); 
    } 

    /* 
    * Constructor which accepts a generic Map for testing 
    */ 
    public TestMap(Map<String, Integer> m) 
    { 
     this.internalMap = m; 
    } 

    public void test() 
    { 
     try 
     { 
      //put some values into the Map 
      this.internalMap.put("Pittsburgh Steelers", 6); 

      this.printMap("Tested Map", this.internalMap); 
     } 
     catch (Exception ex) 
     { 

     } 
    } 
} 
+0

這也是我的想法......但根據我的教授和分級師的說法,TestMap應該是「Generic」,我應該能夠通過每個實例化一個TestMap實例來測試HashMap和TreeMap,然後調用測試()。 –

+0

如果我可以假設鍵/值的類型,它會更有意義... –

+0

在這種情況下,您的測試方法可以根據KeyType和ValueType的類來創建測試變量。 –