简体   繁体   English

在 Java 中将 long 分配给 Long

[英]Assigning long to Long in Java

I am currently going through one of the Android Tutorials .我目前正在阅读Android 教程之一。 I found an expression like:我发现了一个类似的表达式:

Bundle bundle = getIntent().getExtras();
Long longVariable = bundle.getLong(someId);
if( longVariable != null )
{
  //doSomething
}

After looking at Bundle.getLong in the API I saw that it returns a long (primitive).在查看 API 中的 Bundle.getLong 后,我看到它返回一个long (原始)。 Now, I didn't write Java for quite a while, only C# in the meanwhile, but how can the object Long longVariable variable ever be null? Now, I didn't write Java for quite a while, only C# in the meanwhile, but how can the object Long longVariable variable ever be null?

If getLong() really has return type long it can't be, ie l will never be null.如果getLong()真的有返回类型long它不可能是,即l永远不会是 null。 Probably the programmer didn't look up the return type, but inferred from the method name a Long would be returned.可能程序员没有查找返回类型,但从方法名称推断会返回一个Long

What if you pass in the wrong id?如果你输入了错误的id怎么办? Then it is not found, but do you get null, or an exception is raised?然后没有找到,但是你得到null,还是抛出异常? Documentation states that:文档指出:

public long getLong (String key)
Returns the value associated with the given key, 
or 0L if no mapping of the desired type exists for the given key.  
Parameters

     key    a String
Returns
     a long value

So it never returns null, but 0L eventually.所以它永远不会返回 null,但最终会返回 0L。 However, getLongArray returns null sometimes, so it might be a leftover from using getLongArray?但是,getLongArray 有时会返回 null,所以它可能是使用 getLongArray 的剩余部分?

In Java Long is an object and like any object it can be null.在 Java 中, Long是 object 和任何 object 一样,它可以是 Z37A6259CC0C1DAE299A7866489。 long is a primitive type and cannot be null. long是原始类型,不能是 null。

From Java 1.5 on wards Java supports auto-boxing and unboxing meaninng that it's convert between the primitives and objects automatically.从 Java 1.5 起 Java 支持自动装箱和拆箱,这意味着它可以在基元和对象之间自动转换。

If a method returns long then it's probably safe not checking for null even if you cast it to a Long however if a method returns Long object its a good idea to check for nulls.如果方法返回long ,那么即使将其强制转换为Long ,也不检查null可能是安全的,但是如果方法返回Long object,则检查空值是个好主意。

Try creating new instance.尝试创建新实例。 bundle.getLong(someId) returns the primitive long type not Long . bundle.getLong(someId)返回原始long类型而不是Long Long l = new Long(bundle.getLong(someId));

And then check if(l != null)然后检查if(l != null)

Make sure you have extracted the right long from the Bundle .确保您已从Bundle中提取了正确的long Try Log ging this Long object see if it is all right.尝试Log这个Long object 看看是否可以。

Log.i("MY LONG: ", String.valueOf(l));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM