How to convert double to object?

2019-05-07 02:35发布

问题:

I am writing part of my program which read data from a txt file.

I have problem when I want to set value of JSpinner by setValue(object).

My data is double so I need to convert it to object, but how?

LoadData open = new LoadData();
data.setFz(open.giveAwayData());
spinner_1.setValue(data.getFz()); // Fz is double

回答1:

Try casting it to Double (with capital):

spinner_1.setValue((Double) data.getFz());


回答2:

Use Double.valueOf(data.getFz()). An explanation of the differences between primitives and boxed primitives can be found here; basically, primitives have better performance but the boxed classes are there for when you need an Object. A common example is with generics, which cannot be primitives.

However, a double can be passed to something requiring a Double or one of its superclasses. This is because of autoboxing. Yes, I like links a lot.



回答3:

You can use for example the Double constructor to convert double primitive type to a Double object.

Double dObj = new Double(d);

or you can cast it to Double like this:

spinner_1.setValue((Double)data.getFz());