Typed DefaultListModel to avoid casting
Is there a way in java to have a ListModel that only accepts a certain type?
What I'm looking for is something like DefaultListModel<String>
or TypedListModel<String>
, because the DefaultListModel only implements addElement(Object 开发者_运维知识库obj)
and get(int index)
which returns Object
of course.
That way I always have to cast from Object
to e.g. String
and there is no guarantee that there are only strings in my model, even though I'd like to enforce that.
Is this a flaw or am I using list models the wrong way?
The class DefaultListModel does have this up the top in the source:
This class loosely implements the
java.util.Vector
API, in that it implements the 1.1.x version ofjava.util.Vector
, has no collection class support, and notifies theListDataListener
s when changes occur. Presently it delegates to aVector
, in a future release it will be a real Collection implementation.
Sounds like it's just an old class. I guess you could write your own version of it (implement the AbstractListModel interface) if you are desperate enough. If you are just annoyed about having to cast it to a String all the time surely the foreach syntax will do that for you?
精彩评论