Cannot infer type arguments for JList<>



This site utilizes Google Analytics, Google AdSense, as well as participates in affiliate partnerships with various companies including Amazon. Please view the privacy policy for more details.

I was recently adding some type parameters to a raw JList in some old Java code.

The JList I was messing with in particular passed a ListModel - a DefaultListModel to be exact - into its constructor. So, thinking that the JList needed to have the DefaultListModel as its generic type, I set my types as follows (that’s the text between the < and > for my non-programming readers):

DefaultListModel<String> model = new DefaultListModel<>();
JList<DefaultListModel<String>> list = new JList<>(this.model);

Welp, Eclipse didn’t like this. I gave me the following error message:

Cannot infer type arguments for JList<>

Ok? I tried removing the <String> from the DefaultListModel in the JList:

DefaultListModel<String> model = new DefaultListModel<>();
JList<DefaultListModel> list = new JList<>(this.model);

Nope. Eclipse is still telling me:

Cannot infer type arguments for JList<>

Huh. After a little Googlin’ and failing to find anything useful, I take a look at the source code for JList, particularly the constructors. Here are the four constructors for a Jlist:

public JList()
public JList(final E[] listData)
public JList(final Vector<? extends E> listData)
public JList(ListModel<E> dataModel)

Ope. It turns out that the JList simply needs the same type parameter as the DefaultListModel. In other words, this:

DefaultListModel<String> model = new DefaultListModel<>();
JList<String> list = new JList<>(this.model);

Pretty simple, honest mistake and misunderstanding.

Keep in mind I have at least ten years of Java experience and have been playing with programming since I was in the single digits. If you’re new and feel bad because you have to look things up, well, everyone has to look things up.

Leave a Reply

Note that comments won't appear until approved.