Cannot convert from type object to long

2019-02-11 20:07发布

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?

7条回答
地球回转人心会变
2楼-- · 2019-02-11 20:59

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
查看更多
登录 后发表回答