Java ArrayList inheritance problem (looks like a namespace collision)
I'm new to Java (three days spend actually), but I have to write a custom cross-platform editor app as an interface to my database. Everything is running smooth actually, but I've got a strange package error. i开发者_StackOverflow社区nb4 3 years of Python and AS3 programming.
I'm trying to extend a java.util.ArrayList and got stucked into the add method overriding. Code looks somehow like that:
package myxmleditor;
public class BarsList<EditorXMLObject> extends
java.util.ArrayList<EditorXMLObject> {
@Override
public boolean add(EditorXMLObject element) {
editorGUI.addEditorPane(element); // error here
return super.add(element);
}
public EditorGUIInterface editorGUI = null;
}
BarsList, EditorGUIInterface and EditorXMLObject are within the myxmleditor package. The addEditorPane method is
EditorGUIInterface.addEditorPane(EditorXMLObject element)
NetBeans shows me an error:
method addEditorPane in class myxmleditor.TsukasaXMLEditGUI cannot be applied to given types;
required: **myxmleditor.EditorXMLObject**
found: **EditorXMLObject**
reason: actual argument EditorXMLObject cannot be converted to myxmleditor.EditorXMLObject by method invocation conversion
Your class BarsList is not a template. If you would like to make BarsList a list of EditorXMLObject, simple write:
public class BarsList extends java.util.ArrayList<EditorXMLObject>
However if you would like to create another template basing on ArrayList, write:
public class BarsList<T> extends java.util.ArrayList<T>
It's probably best not to subclass ArrayList. Try keeping an ArrayList as a member of BarsList then calling the add yourself.
Using inheritance could make it more difficult to change list implementation at a later date (calling code could use ArrayList specific behaviour). Also, you are dependent on implementation details of ArrayList (as hertzsprung pointed out) and have become responsible for maintaining any contracts made by ArrayList. What should happen when the user calls remove, addAll or clear?
Alternatively, there is so little in the class, it might be easiest just to use the List directly and call addEditorPane manually. This depends on how often and where you call add from though.
Subclassing collections is dangerous because, for example, you don't know whether or not addAll() delegates to add() inside the superclass (this is explained further in Effective Java, p.71).
If you can avoid it, it would be better to create a forwarding collection; Google Guava's ForwardingList could be useful here.
精彩评论