I’m trying to make a class that implements Collection, so it has to have the method that removes an Object, so I figured I’d just reuse the method I already created to remove an object of a generic type T, but it throws a compile-time error. Why won’t this work?
Code
public class ArrayPP<T> implements Collection<T>
{
public boolean remove(Object o)
{
if (o instanceof T)
remove((T)o, true);
else
return false;
return true;
}
}
Error
ArrayPP.java:5: unexpected type
found : T
required: class or array
if (o instanceof T)
Why, Java?
I’ve solved it with
if (t.getClass().isInstance(o))
remove((T)o, true);
else
return false;
return true;
But… I mean if someone codes “ArrayPP<String> a = new ArrayPP<String>();“, you know that T is String, right? So how come, during runtime, it can’t be seen whether o is a String? I mean, if I were to do a.add('c');, it wouldn’t compile, because it knows that, here, the add(T item) method in ArrayPP will only accept Strings, so why… ugh….
For remove, you don’t need to check the type. If the type doesn’t match it won’t be there and remove will return false anyway.
If you want a dynamic check for add(T t) you need to store the type in a field.
Have you looked at Checked Collection in the Collections utility. It may do what you want.
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html under checkedCollection, checkedList, checkedSet, checkedMap