无法从类型对象转换为长整型
我有一个名为 table
的哈希表。类型值为long
。我使用 .values()
获取值。现在我想访问这些值。
Collection val = table.values();
Iterator itr = val.iterator();
long a = (long)itr.next();
但是当我尝试获取它时,它给了我错误,因为我无法从类型 object
转换为 long
。我该如何绕过它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
试试这个:
您最终会得到一个 Long 对象,但通过自动装箱,您几乎可以像原始 long 一样使用它。
另一种选择是使用泛型:
Try this:
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:
Number
类可用于克服数字数据类型转换。在这种情况下,可以使用以下代码:
我准备了以下示例:
对象
到长
示例 - 1控制台输出将是:
< br>
对象
到double
示例 - 2控制台输出将是:
< br>
对象
到双
示例 - 3小心这个简单的错误!如果使用 doubleValue() 函数转换浮点值,则第一个值可能不等于最终值。
如下所示
0.11
!=0.10999999940395355
。控制台输出将是:
对象
到浮动
示例 - 4控制台输出将是:
Number
class can be used for to overcome numeric data-type casting.In this case the following code might be used:
I've prepared the examples below:
Object
tolong
example - 1Console output would be:
Object
todouble
example - 2Console output would be:
Object
todouble
example - 3Be 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
.Console output would be:
Object
tofloat
example - 4Console output would be:
尝试:
long a = ((Long) itr.next()).longValue();
Try :
long a = ((Long) itr.next()).longValue();
您应该使用 Java 5 中的新泛型功能。
您可以阅读此快速 howto 或此更完整的教程。
You should use the new Generics features from Java 5.
You can read this quick howto or this more complete tutorial.
就我而言,我有一个从 Flex 客户端获得的对象数组,
有时这些数字可以被 java 解释为 int,有时也可以解释为 long,
因此为了解决这个问题,我使用“toString()”函数,如下所示:
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:
我在进行 JSP 编码时遇到了同样的问题。上面提到的有关 Long 和泛型的建议要么不起作用,要么不适合代码片段。
我必须像这样解决它(在 JSP 中):
然后使用我的对象 y 像 <%=y%>就像我们在 scriptlet 中使用任何其他 Java 变量一样。
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):
and afterwards use my Object y like <%=y%> as we would use any other Java variable in scriptlet.