我有一个名为table
. 类型值为long
。我正在使用.values()
. 现在我想访问这些值。
Collection val = table.values();
Iterator itr = val.iterator();
long a = (long)itr.next();
但是当我尝试获取它时,它给了我错误,因为我无法从 type 转换object
为long
. 我怎么能绕过它?
我有一个名为table
. 类型值为long
。我正在使用.values()
. 现在我想访问这些值。
Collection val = table.values();
Iterator itr = val.iterator();
long a = (long)itr.next();
但是当我尝试获取它时,它给了我错误,因为我无法从 type 转换object
为long
. 我怎么能绕过它?
尝试这个:
Long a = (Long)itr.next();
您最终会得到一个 Long 对象,但通过自动装箱,您可以像使用原始 long 一样使用它。
另一种选择是使用泛型:
Iterator<Long> itr = val.iterator();
Long a = itr.next();
Number
class 可用于克服数字数据类型转换。
在这种情况下,可能会使用以下代码:
long a = ((Number)itr.next()).longValue();
我准备了以下示例:
Object
示例 long
- 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() );
控制台输出将是:
1416313200307
Object
举 double
个例子 - 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");
控制台输出将是:
0.11
Object
to double
example-3
小心这个简单的错误!如果使用doubleValue()
函数转换浮点值,则第一个值可能不等于最终值。
如下图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");
控制台输出将是:
0.10999999940395355
Object
举例 - 4float
// 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");
控制台输出将是:
0.11
尝试 :long a = ((Long) itr.next()).longValue();
就我而言,我有一个从 flex 客户端获得的对象数组,
有时这些数字可以被java解释为int,有时也可以解释为long,
所以为了解决这个问题,我使用了“toString()”函数,如下所示:
public Object run(Object... args) {
final long uid = Long.valueOf(args[0].toString());
long value = Long.parseLong((String)request.getAttribute(""));
我在进行 JSP 编码时遇到了同样的问题。上面提到的关于 Long 和泛型的建议要么不起作用,要么不适合代码片段。
我不得不像这样解决它(在 JSP 中):
<%Object y=itr.next(); %>
然后像 <%=y%> 一样使用我的 Object y,就像我们在 scriptlet 中使用任何其他 Java 变量一样。