Use can create a List
of java.time.LocalTime
.
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<LocalTime> list = new ArrayList<>();
for (int i = 0; i < 24; i++) {
list.add(LocalTime.of(i, 0));
}
System.out.println(list.get(3));
}
}
Output:
03:00
Learn more about java.time
, the modern date-time API* from Trail: Date Time.
Using legacy API:
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
List<String> list = new ArrayList<>();
for (int i = 0; i < 24; i++) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, i);
calendar.set(Calendar.MINUTE, 0);
list.add(sdf.format(calendar.getTime()));
}
System.out.println(list.get(3));
}
}
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.