Question

I have a combo box like this:

static final String[] intString = {"Dist.","4","5","6","7","8"};
static JComboBox numList = numList = new JComboBox(intString);

And I need to grab which item is selected and convert it to type int. I used this:

Integer.parseInt(numList.getSelectedItem().toString()

But honestly do not understand why it works. If I do not include "toString()," the associated error is:

parseInt(string) in Integer cannot be applied to Object

So, I passed a String and the items in the list are now objects? I understand that when you have a class and instantiate it, you are effectively creating a reference to an object with all the associated methods and instance variables of the class. But I do not understand object creations, when and why, beyond this concept.

Why are the items in a list now objects, and how can you cast an object to a String? I understand that you can pass subclasses when superclasses are referenced:

ArrayList<Object> dogList = new ArrayList<Object>();
Dog yorkie = new Dog(); 
dogList.add(yorkie); //since Dog extends object
Dog doberman = (Dog) dogList[0]; //re-cast to original type

Perhaps the concept is similar.

Thank you.

Was it helpful?

Solution

Integer.parseInt(numList.getSelectedItem().toString()

The getSelectItem() method returns an Object. You get the error messeage (when you don't use the toString() method) because the parseInt() method is expecting a String.

So, I passed a String and the items in the list are now objects?

The Object still is a String, so you could do it this way:

Object selected = numList.getSelectedItem();
String selectedString = (String)selected;
Integer.parseInt( selectedString );

OTHER TIPS

Try:

List<Dog> dogList = new ArrayList<>();

and override the toString():String method in the Dog class.

If you don't have a toString() defined in your custom class, then it may return a pointer to memory for that Object.

getSelectedItem will return a type of Object, which is, obviously, not compatible with the expectations of Interger.parseInt(String).

All classes extend from Object, so everything can be passed and used where Object is expected. It is the lowest common denominator.

One of the methods of Object is the toString method. String#toString simple returns itself.

For example. You are a Human, you are also known as sherrellbc (and presumably other names). So, if I had a method took Human as parameter, I could pass you to it, because you can be cast and treated as a Human.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top