• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics warning

 
Saverio Miroddi
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
}
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Saverio Miroddi
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you :-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic