Cannot convert from type object to long

Mohit BAnsal picture Mohit BAnsal · Feb 28, 2010 · Viewed 79.9k times · Source

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?

Answer

Vincent Ramdhanie picture Vincent Ramdhanie · Feb 28, 2010

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();