坚持使用Java泛型类
我有一个任务,我被卡住了。任务是为此方法编写一个泛型类:坚持使用Java泛型类,java,generics,Java,Generics,我有一个任务,我被卡住了。任务是为此方法编写一个泛型类: public static void main(String[] args) { ValueStore<Object> myStore1 = new ValueStore<Object>(); myStore1.set("Test"); myStore1.get(); /// ValueStore<Object> myStore2 = new ValueSto
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();
}
publicstaticvoidmain(字符串[]args){
ValueStore myStore1=新的ValueStore();
myStore1.设置(“测试”);
myStore1.get();
///
ValueStore myStore2=新的ValueStore();
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;
}
}
公共类ValueStore{
私人信托;
公共无效集(TX){
系统输出println(x);
}
公众得不到(){
返回x;
}
}
我可以打印mystore.set“test”,但不能打印myStore2.set。我不明白为什么我的老师把一个引用变量作为参数传入。当我这么做的时候,我得到了ValueStore@15db9742在控制台中。或许这就是重点
有人能解释为什么上面写着myStore2.set(myStore1);
myStore1=myStore2.get()
,它应该打印什么以及背后的逻辑
先谢谢你。对不起,如果我的文字很乱。第一次在这里。我认为当前您只是缺少了
set()
方法中的一行,如
public void set(T x) {
System.out.println(x);
this.x = x;
}
这样您就可以实际存储该对象了。我已经对其进行了更多的解释。主要的一点是,您可以为
ValueStore
(在本例中为String
)指定一个类型。这使类型系统意识到,当您在valuestore
上调用get()
时,它会得到一个字符串作为回报。这实际上是泛型的全部要点。如果简单地放置对象
,只有您知道get方法将返回一个字符串
,因此您必须强制转换它(如第二个示例所示)
不太清楚你的老师想要什么,但你可以绕过ValueStore@15db9742
在ValueStore
类中实现String-toString(){}
方法的问题。当然ValueStore#set
的实现应该包括this.x=x代码>?
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