2014-09-29 102 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