File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Generics warning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generics warning" Watch "Generics warning" New topic

Generics warning

Saverio Miroddi

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?


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

Joined: Jul 08, 2003
Posts: 24195

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

Joined: Jun 16, 2006
Posts: 21
Thank you :-)
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Generics warning
It's not a secret anymore!