简体   繁体   中英

Casting from a ListModel into a DefaultListModel in Java 7

How can I cast a ListModel to a DefaultListModel??! I perform the following and I get this error message,

DefaultListModel portalListModel = (DefaultListModel) portalList.getModel();

C:\Documents and Settings\...\myfile.java:728: warning: [rawtypes] found raw type: DefaultListModel
    DefaultListModel portalListModel = (DefaultListModel) portalList.getModel();
missing type arguments for generic class DefaultListModel<E>
where E is a type-variable:
E extends Object declared in class DefaultListModel

I tried the following,

DefaultListModel<E> portalListModel = (DefaultListModel) portalList.getModel();

I have a feeling tha this is a stupid question but I'm totally confued with this new generic thing! Please help me out!

The way that Java's Collections work is that you can use Collection-type objects to store a whole bunch of Objects. Prior to the introduction of Generics, you could store any object in a Collection, and then you had to perform a cast when you wanted to get those Objects out of your collection.

List myList = new ArrayList();
myList.add("string");
myList.add(new MyValueClass(42, "identifying string"));

That's perfectly acceptable code. If you wanted to iterate over the objects, you could do it like so:

Iterator it = myList.iterator();
while (it.hasNext()) {
    String str = (String) it.next();  // NOTE: This will work the first time, but throw a ClassCastException when it gets to the second item.
}

With Java 1.5, Generics provides compile-time type checking upon insertion into the list. So now, if you declare myList as a List<String> , the first block of code above will fail at compile time when you attempt to add an object of type MyValueClass to the List.

In Java 1.7, DefaultListModel is genericized. So when you call portalList.getModel() , you're going to get back a DefaultListModel that contains a certain type of object (which is what the <E> is; it's a placeholder for the actual object type.) In the above List<String> example, String is the substitution for E .

So if your portalList object's model member is a DefaultListModel that contains a bunch of MyValueClass objects, then your declaration should look like:

DefaultListModel<MyValueClass> portalListModel = portalList.getModel();

See the DefaultListModel API doc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM