Confusion with templates, generics, and instanceof
I am still in my first year of learning Java, so by all means type
this up as a "newbie" question if you like.
I have started working with templates and generics. I don't fully
understand the underlying mechanics of them. Either because of that or
for whatever other reason, I have been having some problems.
I've tried to distill my problems down to an illustrative test case:
<code>
public class FooWrapper<T> {
//-------------
// Instance variable:
private T foo;
//-------------
// Constructor:
public FooWrapper(T foo) {
this.foo = foo;
}
// Getter:
public T getFoo() {
return foo;
}
}
</code>
The above code seems perfectly fine. However, suppose I try writing an
equals method. Two possibilities come to mind. The first looks like
this:
<code>
public boolean equals(Object o) {
boolean result = false;
if (o instanceof T) {
T t = (T)(o);
if (foo.equals(t.getFoo())) {
result = true;
}
}
return result;
}
</code>
Basically this doesn't work because "o instanceof T" (where T is a
template) doesn't work.
The other possibility is:
<code>
public boolean equals(T t) {
boolean result = false;
if (foo.equals(t.getFoo())) {
result = true;
}
return result;
}
</code>
I don't know why this doesn't work, but Eclipse says the following:
(1) "Name clash: The method equals(T) of type FooWrapper<T> has the
same erasure as equals(Object) of type Object but does not override
it"
(2) "The method getFoo() is undefined for the type T"
-----------------------
What in the heck is the solution here? Can anybody help?
Greg