技术开发 频道

JAVA:3个常用的JDK对象详细解析

  ⑤ 移位运算:

 1     public static void main(String args[]) {
2 byte[] bytes = new byte[] { 0x1, 0x00, 0x00 };
3 BigInteger bi = new BigInteger(bytes);
4 System.out.println(bi);
5 //右移一位
6 System.out.println("after shift right is " + bi.shiftRight(1));
7 //左移3位
8 System.out.println("after shift left is " + bi.shiftLeft(3));
9 //翻转第三位,既如果第三位(0 based)为0,则翻转为1,反之翻转为0.
10 //翻转之前:10000000000000000
11 //翻转之后:10000000000001000
12 bi = bi.flipBit(3);
13 System.out.println("after flip is " + bi);
14 //将第三位的bit清0
15 //clear之前:10000000000001000
16 //clear之后:10000000000000000
17 bi = bi.clearBit(3);
18 System.out.println("after clear is " + bi);
19 //将第三位设置为1
20 //set之前:10000000000000000
21 //set之后:10000000000001000
22 bi = bi.setBit(3);
23 System.out.println("after set is " + bi);
24 System.out.println("The binary result for bi is " + bi.toString(2));
25 System.out.println("The test result for BIT 2 is " + bi.testBit(2));
26 System.out.println("The test result for BIT 3 is " + bi.testBit(3));
27 }
28 /* 输出结果如下:
29 65536
30 after shift right is 32768
31 after shift left is 524288
32 after flip is 65544
33 after clear is 65536
34 after set is 65544
35 The binary result for bi is 10000000000001000
36 The test result for BIT 2 is false
37 The test result for BIT 3 is true
38 */

  时区

  如果你的产品面向全世界的每一个角落,或者说你接到外包项目可能来自多个不同的国家,那么你的程序将会面临时区问题。

  ① 基于不同时区设置本地时区的Calendar

 1     public static void main(String args[]) {
2 //获取基于日本时区的Calendar对象。
3 Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));
4 japanCal.set(Calendar.HOUR_OF_DAY, 10); // 0..23
5 japanCal.set(Calendar.MINUTE, 0);
6 japanCal.set(Calendar.SECOND, 0);
7 //本地时区为北京时区
8 Calendar local = new GregorianCalendar();
9 local.setTimeInMillis(japanCal.getTimeInMillis());
10 int hour = local.get(Calendar.HOUR);
11 int minutes = local.get(Calendar.MINUTE);
12 int seconds = local.get(Calendar.SECOND);
13 System.out.println("Hours = " + hour + "\tMinutes = " + minutes
14 + "\tSeconds = " + seconds);
15 }
16 /* 输出结果如下:
17 Hours = 9 Minutes = 0 Seconds = 0
18 */

  和预想的一样,我们通过日本时区设置时间后,在通过该Calendar来设置本地时区的Calendar,结果是得到正确的本地时间,换句话说,时区参与了时间的计算。因此可以说,Calendar对象在生成小时部分的时间时,会结合当时的时间和本地的时区来构造该部分,当时区切换时,Calendar会根据初始的时区、初始的时间和当前的时区来进行推算并给出结果。

  ②获取本地时区和所有可用时区:

1     public static void main(String args[]) {
2         //获取本地时区
3         Calendar now = Calendar.getInstance();
4         TimeZone timeZone = now.getTimeZone();
5 System.out.println("Current TimeZone is : " + timeZone.getDisplayName());
6         //获取系统当前所有可用的时区
7         String[] availableTimezones = TimeZone.getAvailableIDs();
8         for (String timezone : availableTimezones) {
9           System.out.println("Timezone ID = " + timezone);
10         }
11     }
12     /*    输出结果如下:
13         Current TimeZone is : 中国标准时间
14         Timezone ID = Etc/GMT+12
15         Timezone ID = Etc/GMT+11   
16         ... ...
17     */
0
相关文章