2014-09-29 103 views
2

我有一個任務,我卡住了。這個任務是爲這個方法編寫一個通用類:卡住了Java通用類

public static void main(String[] args) { 
    ValueStore<Object> myStore1 = new ValueStore<Object>(); 
    myStore1.set("Test"); 
    myStore1.get(); 

    /// 
    ValueStore<Object> myStore2 = new ValueStore<Object>(); 
    myStore2.set(myStore1); 
    myStore1 = myStore2.get(); 
} 

我來到這裏了。

public class ValueStore<T> { 
    private T x; 

    public void set(T x) { 
     System.out.println(x); 
    } 

    public T get() { 
     return x; 
    } 
} 

我能打印出mystore.set「test」,但不能打印myStore2.set。我不明白爲什麼我的老師通過一個參考變量作爲參數。當我這樣做時,我在控制檯中獲得ValueStore @ 15db9742。或者也許這就是重點?

有人可以解釋爲什麼它說myStore2.set(myStore1); myStore1 = myStore2.get(),它應該打印什麼和它背後的邏輯?

預先感謝您。對不起,如果我的文字是混亂的。第一次來這裏。

+0

不太清楚你的老師想要什麼,但你可以通過實現一個'字符串的ToString(避開'ValueStore @ 15db9742'問題){}'方法在你的'ValueStore'類中。 – OldCurmudgeon 2014-09-29 09:09:47

+5

當然,'ValueStore#set'的實現應該包含'this.x = x;'? – 2014-09-29 09:10:52

回答

2

我覺得目前你只是缺少從set()一種線條,如

public void set(T x) { 
    System.out.println(x); 
    this.x = x; 
} 

所以,你會實際存儲的對象。

0

我已經評論了一些更多的解釋。主要的一點是,你可以給你的ValueStore輸入一個類型(在本例中爲String)。這使得類型系統知道當您在valuestore上調用get()時,它會得到一個string作爲回報。這實際上就是泛型的全部要點。如果你簡單地把object,只有你知道get方法將返回String所以你必須投它(如第二個例子)。

public static void main(String[] args) { 
    // Type your store with String, which is what generics is about. 
    ValueStore<String> myStore1 = new ValueStore<String>(); 

    // Store a string in it. 
    myStore1.set("Test"); 
    // Get the object, and the typesystem will tell you it's a string so you can print it. 
    System.out.println(myStore1.get()); 

    /// 
    ValueStore<Object> myStore2 = new ValueStore<Object>(); 
    // Store your store. 
    myStore2.set(myStore1); 
    // The type system only knows this will return an Object class, as defined above. 
    // So you cast it (because you know better). 
    myStore1 = (ValueStore<String>) myStore2.get(); 
    System.out.println(myStore1.get()); 
} 

public class ValueStore<T> { 
    private T x; 

    public void set(T x) { 
     this.x = x; 
    } 

    public T get() { 
     return x; 
    } 
} 

此代碼打印如下:

test 
test 
+0

很好的解釋和寫得很好。謝謝你,兄弟! – Kharbora 2014-09-29 09:25:57