1. Calendar:
对于每一个Java的开发者而言,这是一个再熟悉不过的对象了,这里我们给出一个巧妙的例子,至于如何巧妙,看了输出结果就清楚了。
1 public class MyTest {
2 public static void main(String args[]) {
3 GregorianCalendar d = new GregorianCalendar();
4 int today = d.get(Calendar.DAY_OF_MONTH);
5 int month = d.get(Calendar.MONTH);
6 // set d to the first date of the month
7 d.set(Calendar.DAY_OF_MONTH, 1);
8 int weekday = d.get(Calendar.DAY_OF_WEEK);
9 // get first day of week(Sunday in the U.S.)
10 int firstDayOfWeek = d.getFirstDayOfWeek();
11 // determine the required indentation for the first line
12 int indent = 0;
13 while (weekday != firstDayOfWeek) {
14 ++indent;
15 d.add(Calendar.DAY_OF_MONTH, -1);
16 weekday = d.get(Calendar.DAY_OF_WEEK);
17 }
18 // print weekday names
19 String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
20 do {
21 System.out.printf("%4s", weekdayNames[weekday]);
22 d.add(Calendar.DAY_OF_MONTH, 1);
23 weekday = d.get(Calendar.DAY_OF_WEEK);
24 } while (weekday != firstDayOfWeek);
25 System.out.println();
26
27 for (int i = 1; i <= indent; ++i)
28 System.out.print(" ");
29
30 d.set(Calendar.DAY_OF_MONTH, 1);
31 do {
32 // print day
33 int day = d.get(Calendar.DAY_OF_MONTH);
34 System.out.printf("%5d", day);
35 // mark current day with *
36 if (day == today)
37 System.out.print("*");
38 else
39 System.out.print(" ");
40 // advance d to the next day
41 d.add(Calendar.DAY_OF_MONTH, 1);
42 weekday = d.get(Calendar.DAY_OF_WEEK);
43 // start a new line at the start of the week
44 if (weekday == firstDayOfWeek)
45 System.out.println();
46 } while (d.get(Calendar.MONTH) == month);
47 // the loop exists when d is day 1 of the next month
48
49 // print final end of line if neccessary
50 if (weekday != firstDayOfWeek)
51 System.out.println();
52 }
53 }
54 /* 输出结果如下:
55 星期日 星期一 星期二 星期三 星期四 星期五 星期六
56 1 2 3
57 4 5 6 7* 8 9 10
58 11 12 13 14 15 16 17
59 18 19 20 21 22 23 24
60 25 26 27 28 29 30
61 */
复制代码
2. java.utils.Arrays:
该类为我们提供了很多操作数组的方法,他们都是非常方便且高效的,很多时候比我们自行实现的数组操作要高效的多,然而有的时候它却并不为我们所熟知。记得我第一次用到他们的时候,那时我已经使用Java开发有一段时间了,当时的感觉立刻使我想起了很多C语言的CRT函数,如memset、memcpy等,还有一些C++标准库中用到的泛型算法,确实有一种一见如故的感觉。这里只是列出了一些常用的静态域方法,还需要提醒的是Java的集合框架中也提供了Collections工具类,其作用和Arrays有些相仿,只是主要作用于集合框架中的各个容器类。
int binarySearch(type[] a,type key)
这个方法查询key元素值在a数组中出现的索引;如果a数组不包含key元素值,则返回负一。调用该方法时要求数组中元素已经按升序排列,这样才能得到正确结果。
binarySearch(type[] a,int fromIndex,int toIndex,typ