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:40

I faced the same problem but while doing JSP coding. The above mentioned suggestions regarding Long and generics either did not work or did not fit into the code fragment.

I had to solve it like this(in JSP):

<%Object y=itr.next(); %>

and afterwards use my Object y like <%=y%> as we would use any other Java variable in scriptlet.

查看更多
ら.Afraid
3楼-- · 2019-02-11 20:43

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();
查看更多
smile是对你的礼貌
4楼-- · 2019-02-11 20:46

in my case I have an array of Objects that I get from a flex client,

sometimes the numbers can be interpreted by java as int and sometimes as long,

so to resolve the issue i use the 'toString()' function as follows:

public Object run(Object... args) {

  final long uid = Long.valueOf(args[0].toString());
查看更多
淡お忘
5楼-- · 2019-02-11 20:47

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.

查看更多
beautiful°
6楼-- · 2019-02-11 20:49
long value = Long.parseLong((String)request.getAttribute(""));
查看更多
Root(大扎)
7楼-- · 2019-02-11 20:53

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

查看更多
登录 后发表回答