Reputation: 85
I have an assignment and I'm stuck. The assignment is to write a generic class for this method:
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();
}
I've come this far.
public class ValueStore<T> {
private T x;
public void set(T x) {
System.out.println(x);
}
public T get () {
return x;
}
}
I am able to print out mystore.set "test", but not the myStore2.set. And I don't understand why my teacher passed in a reference variable as a argument. When I do that I get ValueStore@15db9742 in the console. Or maybe thats the point?
Can someone explain why it says myStore2.set(myStore1);
myStore1 = myStore2.get()
, what it should print and the logic behind it?
Thank you in advance. And sorry if my text is all messy. First time here.
Upvotes: 2
Views: 162
Reputation: 2922
I have commented a bit more to explain. The main point is that you can give a type to your ValueStore
(in this example, String
). This makes the typesystem aware that when you call get()
on the valuestore
, it gets a string
in return. This is actually the entire point of generics. If you simply put object
, only you know that the get method will return a String
so you would have to cast it (as in the second example).
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;
}
}
This code prints the following:
test
test
Upvotes: 0
Reputation: 81539
I think currently you are just missing a line from your set()
method, as in
public void set(T x) {
System.out.println(x);
this.x = x;
}
So that you would actually store the object.
Upvotes: 2