| Author |
Generics warning
|
Saverio Miroddi
Greenhorn
Joined: Jun 16, 2006
Posts: 21
|
|
I'm writing a listmodel subclass with an arraylist of key/values. So I wrote this, but got the warning and the error written in the code. Why do they happen? Also, is this the rught way of managing a list of keys/values in a jlist? Thanks! class ArrayListModel<K, V> extends DefaultListModel { java.util.ArrayList<Line> list; public ArrayListModel(K[] keys, V[] values) { if (keys.length != values.length) { throw new RuntimeException("Different size arrays"); } for (int i = 0; i < keys.length; i++) { // warning: type safety: the constructor ArrayListModel.Line(Object,Object) // belongs to raw type ArrayListModel.Line. References to generic type // ArrayListModel<K,V>.Line<K,V> should be parametrized list.add(new Line(keys[i], values[i]));} } public Object getElementAt(int index) { return list.get(index).k; } // error: cannot convert from Object to V public V getValueAt(int index) { return list.get(index).v; } private static class Line<K, V> { K k; V v; public Line(K k, V v) { this.k = k; this.v = v; } } }
|
Using a text editor for programming.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24051
|
|
In both places where you refer to a Line, you omit the type parameters. The declaration of "list" should be java.util.ArrayList<Line<K, V>> list; and the line where you construct a Line should be list.add(new Line<K, V>(keys[i], values[i])); } That should take care of all the problems.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Saverio Miroddi
Greenhorn
Joined: Jun 16, 2006
Posts: 21
|
|
|
Thank you :-)
|
 |
 |
|
|
subject: Generics warning
|
|
|