2014-10-17 18 views
1

請在java中使用new。java中的參數化類型的打印值

我想了解泛型它很順利,直到我來到這個:

Pair<Integer, GenericBox<String>> p2 = new OrderedPair<>(1, new GenericBox<>("Parametized Type"); 
p2.print(); 

打印方式:

public void print() { 
    System.out.println(this.key + ", " + this.value); 
} 

它的工作原理,除了當我用parametized類型參數的罰款。

輸出示例:

1, [email protected] 

預期輸出:

1, Parametized Type 

嘗試這樣做:How to get type parameter values using java reflection?但它只是給了我ķ這是OrderedPair'參數

這是我第一次這裏的問題,如果有些我想念的東西或者不清楚的東西,反饋非常感謝。

+1

您需要重寫GenericBox類的toString – 2014-10-17 02:48:52

回答

2

這與泛型沒有任何關係。隨着

this.value 

你大概是指你傳遞給OrderedPair構造的GenericBox對象。這個類(GenericBox)不能有一個聲明toString()方法。因此它繼承和使用Object#toString()

開發人員可以自行編寫toString()實現並返回他們認爲合適的任何String值。 Here's what the official tutorials have to say.