- CourseSession
- Enrolling Students
- int
- Initialization
- Default Constructors
- Suites
- The SDK and java.util.ArrayList
- Adding Objects
- Incremental Refactoring
- Objects in Memory
- Packages and the import Statement
- The java.lang Package
- The Default Package and the package Statement
- The setUp Method
- More Refactoring
- Class Constants
- Dates
- Overloaded Constructors
- Deprecation Warnings
- Refactoring
- Creating Dates with Calendar
- Comments
- Javadoc Comments
- Exercises
Creating Dates with Calendar
You still receive deprecation warnings each time you compile. Bad, bad. You should get rid of the warnings before someone complains. The benefit of having moved the date creation into a separate method, createDate, is that now you will only have to make a change in one place in your code, instead of two, to eliminate the warnings.
Instead of creating a Date object using the deprecated constructor, you will use the GregorianCalendar class. You can build a date or timestamp from its constituent parts by using the set method defined in Calendar. The API documentation for Calendar lists the various date parts that you can set. The createDate method builds a date by supplying a year, a month, and a day of the month.
Date createDate(int year, int month, int date) { GregorianCalendar calendar = new GregorianCalendar(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, date); return calendar.getTime(); }
The GregorianCalendar is a bit more sensible than Date in that a year is a year. If the real year is 2005, you can pass 2005 to the calendar object instead of 105.
You will need to modify the import statements in CourseSessionTest in order to compile and test these changes. The simplest way is to import everything from the java.util package:
import java.util.*;
Compile and test. Congratulations—no more embarrassing deprecation warnings!