Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Conversion from JList to java.util.List

 
Rhett Place
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to pass the contents of a JList from one pane of a GUI to a logic class behind the scenes. Since JList is for GUI's, I need to convert all of it's elements to just a List (java.util.List) for logic processing. The following line compiles just fine but I get a runtime error...



The error is...

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

I have tried many different work-arounds, short of iterating through the list and .add'ing each element to the List.

Any help would be greatly appreciated.
 
Rhett Place
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As it turns out, I needed to iterate the JList anyway because I needed to be able to remove elements from the List and this is not allowed using the .asList() method. I still am curious as to why I could compile but I got a runtime error. I know that all of the Objects are strings, it just won't allow the casting in that context.
 
Paul Clapham
Sheriff
Posts: 21892
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There aren't any workarounds. The toArray() method returns an array of Objects, not an array of Strings. And that is because the ListModel can contain any kind of objects, it isn't restricted to strings.

Now probably you only put Strings in there. The only way (as far as I know) to convert an Object[] to a String[] is to copy the entries one at a time.
 
Brian Cole
Author
Ranch Hand
Posts: 924
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rhett Place:
Since JList is for GUI's, I need to convert all of it's elements to just a List (java.util.List) for logic processing.


Well not necessarily. If you call yourList.getModel() it will return something that is sort of like a java.util.List that is divorced from the GUI. It won't support removal, though.

If you do something like this:
DefaultListModel myModel = new DefaultListModel();
JList myList = new JList(myModel);
then you can call myModel.remove() and so on.

You could even create a custom class that extends java.util.ArrayList and implements ListModel if you needed to.
 
Rhett Place
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good info from both. You each supported the same conclusions that I had come to myself. I just wanted to be sure that I wasn't missing something simple. Thanks for the help.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!