views:

648

answers:

3

Hi 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 cant convert from type object to long. How can i go around it.

Thanks

+6  A: 

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();
Vincent Ramdhanie
+1  A: 

Try : long a = ((Long) itr.next()).longValue();

missingfaktor
This is more long-winded than it needs to be - see the other answer which refers to autoboxing.
crazyscot
@crazyscot: From OP's code I assumed he's using an older version of Java than Java 5.
missingfaktor
+3  A: 

You should use the new Generics features from Java 5.

When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

You can read this quick howto or this more complete tutorial.

Desintegr