Why create new Date object?


#1

I probably should have asked this question when we first wrote Crime.java, but Listing 17.5 reminds me. Why do we create a new Date object to save as mDate?

public Crime(JSONObject json) throws JSONException { ... mDate = new Date(json.getLong(JSON_DATE); }

mDate is already an instance of Date, right? The same way mTitle is already an instance of String. Why can’t we just:


#2

I am curious about this as well. Anyone know?

thanks


#3

Basically that code says:

Date = (Date) long;

Since there is no operator overloading in Java, you can’t do this. In Eclipse, I get an error on that instruction “Cannot cast from long to Date”.

You can do this:

mDate = new Date(); mDate.setTime(json.getLong(JSON_DATE));


#4

RickDroid mostly covers it above, but to elaborate:

In Java, there are two basic types of values you can assign to variables: object references (like mDate) and primitive values (like what gets returned from getLong(String)).

A “long” is just a few bytes in memory that can hold a big number. A “Date” is an instance of the class Date and has potentially several instance variables (it is like Crime in this sense). There is no way for the compiler to know how to directly convert a long into a Date, so we use the constructor for Date that takes in a long as an argument.

That way we have an instance of the class Date to store in the Crime’s member variable mDate. In fact, the mDate variable is just holding a reference to an instance of Date. The data for the instance of Date is actually stored in heap memory somewhere, and the mDate variable is treated like a pointer to that location.