Difference between Long and long?
I am going through the 2nd exercise of the android example the notepad app, I have this a question about the difference between Long and long that was used to define the mRowId.
The exercise is here: http://developer.android.com/resources/tutorials/notepad/notepad-ex2.html
And below is the code piece that I am having problem with:
public class NoteEdit extends Activity {
private Long mRowId;
private Ed开发者_如何学CitText mTitleText;
private EditText mBodyText;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.note_edit);
setTitle(R.string.edit_note);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = null;
When I declared mRowId with long
, I got an error when I tried to set mRowId to null, the error is "type mismatch". But if I use Long
, the error goes away. Why doesn't long
work?
Long
is a wrapper class around the primitive long
. Therefore Long
is an object; objects can be null
, primitives can not.
See the Long
class documentation.
long
is primitive type and Long
is boxed type of long
. After auto-boxing feature is released in java the primitive long
can be automatically converted to Long
, which is an object.
But sometmimes this creates issue also. For example the below code is terribly slow:
public static void main(String[] args)
{
Long sum = 0L;
for(long i=0; i < Integer.MAX_VAL; i++){
sum+=i;
}
}
This is because the program unintentionally creating 2^31 objects unnecessarily because of capital L in sum
declaration.
精彩评论