I don’t understand the following code:
public class EventAdapter extends ArrayAdapter<Event>
{
public EventAdapter(Context context, int textViewResourceId,
List<Event> objects)
{
super(context, textViewResourceId, objects);
this.resource = textViewResourceId;
}
}
I am confused about the <Event> part in both cases. I understand it has something to do with Generics, but I don’t understand it. I read http://docs.oracle.com/javase/tutorial/java/generics/, but still don’t understand.
I do understand that objects is an ArrayList of objects of the type Event.
The part I don’t understand is extending an ArrayAdapter with the Type <Event>. What does this signify?
extends ArrayAdapter<Event>The type restriction here will influence on the return types of methods in the class, and the argument types of methods.
Here is an example, if you have a class:
And if you have another class:
If you remove the
@Overrideannotation, it will run. But theextends SomeClassis useless and might cause problem if you keep it there — there will be two very similar methods:setValue(Event)andsuper.setValue(T). Now the question is will the subclass have access to thesuper.setValue(T)method? I will explain it in the end, see “A missing type parameter bounding example”.So, you need to specify the type in declaration:
Also, if you declare an inconsistent type:
So the type restricts the behavior of class body.
A missing type parameter bounding example:
If I comment
method()in the subclass, it is compiled with a warning:Test.java uses unchecked or unsafe opertations. In the running result, it turned the generic typeTintoObject:public void Test.method(java.lang.Object).If I only uncomment the first
method()in the subclass, it is compiled with no warnings. In the running result, the subclass owns onepublic void Test.method(java.lang.Object). But it doesn’t allow@Overrideannotation.If I only uncomment the second
method()in the subclass (which also has a generic type bounding), the compile fails with an error:name clash. It also doesn’t allow@Overrideannotation. If you do so, it throws a different error:method does not override.method2()is inherited by the subclass unanimously. But you also can’t write the following code:in superclass:
public void method2 (Object obj)and in subclass:public <T> void method2 (T obj). They are also ambiguous and is not allowed by the compiler.