I have a hashtable named table
. The type value is long
. I am getting values using .values()
. Now I want to access these values.
Collection val = table.values();
Iterator itr = val.iterator();
long a = (long)itr.next();
But when I try to get it, it gives me error because I can't convert from type object
to long
. How can I go around it?
A better way to convert your long primitive to the Long object is by using static factory methods like Long. valueOf(long l), which was originally meant to convert long primitive values to a Long object, prior to Java 5, but, also works fine with int primitive.
We can convert String to long in java using Long. parseLong() method.
Convert Object to String in java using toString() method of Object class or String. valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string.
Try this:
Long a = (Long)itr.next();
You end up with a Long object but with autoboxing you may use it almost like a primitive long.
Another option is to use Generics:
Iterator<Long> itr = val.iterator();
Long a = itr.next();
Number
class can be used for to overcome numeric data-type casting.
In this case the following code might be used:
long a = ((Number)itr.next()).longValue();
I've prepared the examples below:Object
to long
example - 1
// preparing the example variables
Long l = new Long("1416313200307");
Object o = l;
// Long casting from an object by using `Number` class
System.out.print(((Number) o).longValue() );
Console output would be:
1416313200307
Object
to double
example - 2
// preparing the example variables
double d = 0.11;
Object o = d;
// Double casting from an Object -that's a float number- by using `Number` class
System.out.print(((Number) o).doubleValue() + "\n");
Console output would be:
0.11
Object
to double
example - 3
Be careful about this simple mistake! If a float value is converted by using doubleValue()
function, the first value might not be equal to final value.
As shown below 0.11
!= 0.10999999940395355
.
// preparing the example variables
float f = 0.11f;
Object o = f;
// Double casting from an Object -that's a float number- by using `Number` class
System.out.print(((Number) o).doubleValue() + "\n");
Console output would be:
0.10999999940395355
Object
to float
example - 4
// preparing the example variables
double f = 0.11;
Object o = f;
// Double casting from an Object -that's a float number- by using `Number` class
System.out.print(((Number) o).floatValue() + "\n");
Console output would be:
0.11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With