Java:为什么“长”原始类型不接受一个简单的数字? [英] Java: why the "long" primitive type does not accept a simple number?

查看:144
本文介绍了Java:为什么“长”原始类型不接受一个简单的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法接收 long 类型参数,我试图调用它传递 1

  contato.setId(1); 

我收到:

  Contato类型中的方法setId(Long)不适用于参数(int)。 

但是, 1 数字以及?不是它内部的范围



PS:只是说,我解决了这个代码的问题:

  Integer y = 1; 
long x = y.longValue();
contato.setId(x);

这只是个简单的问题。

解决方案

long 是一个包含64位的数据类型(不要与对象 Long !)和一个int(32位),所以你不能使用 int long 。请参阅: http://docs.oracle.com/javase/tutorial/java /nutsandbolts/datatypes.html



为了查看如何声明各种数据类型,您应该特别检查下表

 数据类型默认值
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char'\\\'
对象null
布尔值false

,对于你的情况, long 应该用数字后跟一个 L 来声明,例如:

  long x = 100L; 

此外,做你正在做的事情 autoboxing

  Integer y = 1; 
long x = y.longValue();

不仅不必要 - 这也是非常浪费。所以,例如,如果你将在一个循环(许多次),你的代码将是更慢的数量级!


I got a method that receives a long type parameher, and I try to call it passing 1:

contato.setId(1);

And I receive this:

The method setId(Long) in the type Contato is not applicable for the arguments (int).

But, isn't 1 a long number as well? Isn't it inside the long scope??

PS: Just to say, I solved the problem with this code:

Integer y = 1;
long x = y.longValue();
contato.setId(x);

It's just a didatic question.

解决方案

long is a datatype that contains 64bits (not to be confused with the Object Long!) vs. an int (32 bits), so you can't use a simple assignment from int to long. See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

In order to see how to declare the various datatypes, you should check specifically the following table:

Datatype    Default Value
byte        0
short       0
int         0
long        0L
float       0.0f
double      0.0d
char        '\u0000'
Object      null
boolean     false

So, for your case, long should be declared with the number followed by an L, for instance:

long x = 100L;

Further, doing what you're doing with autoboxing:

Integer y = 1;
long x = y.longValue();

is not only unnecessary - it's very wasteful as well. So, for example, if you'll do it in a loop (many times) your code will be slower in order of magnitude!

这篇关于Java:为什么“长”原始类型不接受一个简单的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆