Java 第八天 笔记

1   常用类

     基本类型的包装类  : java 并不是纯面向对象的语言。Javas是一个面向对象的语言,但是Java中的基本数据类型却不是面向对象的。但是我们实际使用中经常将基本数据转化为对象,便于操作,比如:集合的操作,这时我们就行需要将基本类型转化为对象。 Java中的基本类型功能简单,不具备对象的特性,为了使基本类型具备对象的特性,所以出现了包装类,就可以像操作对象一样操作基本类型数据。

   基本类型对应的包装类

  基本类型                  包装类型

  byte          Byte

  int                                 Integer

  short                            Short

  long                              Long

  float                               Float

  double                          Double

  boolean                        Boolean

  char                               Character

A.创建一个包装类对象:

Integer    i = new Integer(4);//创建了一个Integer对象,表示指定的int值

Integer    s = new Integer("8");//创建了一个Integer对象,表示String 参数"8"指定的int 值

包装类常用的方法如下:

包装类主要是两种方法,一种是本类型和其它类型之间进行转换,另一种是字符串和本类型以及基本类型之间的转换

如上图中的方法前五种是本类型和其他类型之间的转换,后三种是字符串和本类型以及基本类型之间的转换。

Double  d = new Double(5);

        byte d1 = d.byteValue();

        System.out.println(d1);

 

Double  d = new Double(5);

      Byte d1 = d.byteValue();

      System.out.println(d1);

 

这两种都是可以的,本类型和其他类型之间的转换,可是为什么上面两个都可以呢?这便是接下来要讲的

B.基本类型与包装类型之间的转换

JDK1.5引入了自动装箱和拆箱的机制,那么什么是装箱和拆箱呢?

装箱:就是将基本类型转换成包装类,分为自动装箱和手动装箱

int a1=4;

//        //手动装箱

//        Integer ai = new Integer(a1);

//        //自动装箱

拆箱:就是将包装类型转换成基本类型,分为自动拆箱和手动拆箱

手动拆箱

//        int ah = ai.intValue();

//        //自动拆箱

//        int ag = ai;

 

没有什么能够阻挡它们之间的转换。

C.字符串和本类型以及基本类型之间的转换

c1.基本类型转换成字符串类型

    c1a.包装类 的toString()方法

    c1b.String 类的valueOf()方法

    c1c.空字符串加一个基本类型变量

 

c2.字符串转换成基本类型

        c2a.包装类的parse***()静态方法

         c2b.包装类的valueOf()方法

//        Integer aj = a1;

//基本类型转换成字符串类型有三种方法

int b = 1;

String b1 = Integer.toString(b);

String b2 = String.valueOf(b);

String b3 = b+"";

System.out.println("b1:  "+b1+"b2: "+b2+"b3: "+b3);

//字符串转换成基本类型的方法有两种

int c1 = Integer.parseInt(b1);

int c2 = Integer.valueOf(b2);

因为存在自动装箱和自动拆箱,所以包装类型和基本类型一样

 实例:

public class Test001 {

    public static void main(String[] args) {
//        Integer i = new Integer(1000);
//        System.out.println(Integer.MAX_VALUE);
//        System.out.println(Integer.toHexString(i));//转化为16进制
//        Integer i2= Integer.parseInt("123"); //将数字字符串转化为数字
//        Integer i3 = new Integer("123");  //初始化转化
//        System.out.println(i3+10);
//        System.out.println(i2.intValue());
//        Double  d = new Double(5);
//        byte d1 = d.byteValue();
//        System.out.println(d1);
//        Double  d2 = new Double(5);
//        Byte d11 = d2.byteValue();
//        System.out.println(d11);
        //基本类型转换成字符串类型有三种方法
        int b = 1;
        String b1 = Integer.toString(b);
        String b2 = String.valueOf(b);
        String b3 = b+"";
    //    System.out.println("b1:"+b1+"\tb2:"+b2+"\tb3:"+b3);
        //字符串转换成基本类型的方法有两种
        int c1 = Integer.parseInt(b1);
        int c2 = Integer.valueOf(b2);
    //    System.out.println(c1+c2);  //结果是2  而不是11
        //装箱
        Integer a = new Integer(1000);//手动装箱
        Integer a1 = 1000;//自动装箱   编译器执行自动操作        
        //拆箱
        Integer t = 2000;
        int c  = t;//自动拆箱子
        int c6 = t.intValue(); //手动拆箱
    
        Integer f1 = 100;
        Integer f2 = 100;
        System.out.println(f1 == f2); //true   在-128到127 之间按照基本类型处理数据
        System.out.println(f1.equals(f2));//true
        Integer f3 = 1000;
        Integer f4 = 1000;
        System.out.println(f3 == f4);//false   //超出-128到127按照类对象处理
        System.out.println(f3.equals(f4));//true
        //System.out.println(c6);
    }

}
2  Date类 

     

1. 概述

(1)Date类是表示特定时间点的对象,精确到毫秒。

As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

JDK1.1及更新版本,应使用Calendar类来转换时间和日期,而DateFormat类来格式化日期或解析关于日期的字符串。此时Date类中相应的方法将被废弃。

(2) 构造器

  • 以当前时间创建对象
    Date()
  • 以指定纪元时间创建对象
    Date(long date)(
  • (3)常用方法
  • 判断时间点的先后
    boolean  after(Date when)
    boolean  before(Date when)
  • 获取或设置纪元时间
    long  getTime()
    void  setTime(long time)

(4) 示例

Date date = new Date(1420000000000l);  // 纪元毫秒时间转换日期对象

long millisTime = date.getTime();  // 日期对象转换纪元毫秒时间

3  Calendar类

     Calendar类是个日历表示法的抽象类,可以通过其静态方法获取当前时间日期的对象。   Calendar类维护了非常多的字段,可以提供关于日历的各种信息以及转换方法。

   实际上,通过静态方法获得的Calendar对象为其子类GregorianCalendar对象,所以也可以直接创建其子类对象进行处理。

(1)年,月,日
YEAR,MONTH,DAY_OF_MONTH/DATE

  • 时,分,秒,毫秒
    HOUR_OF_DAY,MINUTE,SECOND,MILLISECOND
  • 本周星期几,本年第几天,本月第几周,本月第几个7天,本年第几周
    DAY_OF_WEEK,DAY_OF_YEAR,WEEK_OF_YEAR,DAY_OF_WEEK_IN_MONTH,WEEK_OF_YEAR
  • 公元,上下午
    ERA,AM_PM
  • 12小时计时
    HOUR
  • 星期(DAY_OF_WEEK取值范围)
    SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY
  • 月份(MONTH取值范围,其中JANUARY为0)
    JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER

(2)常用方法

  • 使用当前日期时间以及默认时区本地化获取日历对象
    static Calendar  getInstance();
  • 获取/设置当前日历的时间
    Date  getTime()
    void  setTime(Date date)
  • 按毫秒单位时间设置日历时间
    void  setTimeInMillis(long millis)
  • 获取指定字段的值
    int  get(int field)
  • 更改指定字段的值
    void  set(int field, int value);
    void  set(int year, int month, int date)
    void  set(int year, int month, int date, int hourOfDay, int minute)
    void  set(int year, int month, int date, int hourOfDay, int minute, int second)
  • 按给定的偏移更改当前日期时间
    abstract void  add(int field, int amount)
  • 获取该日期指定字段的最大值或最小。
    int  getActualMaximum(int field)
    int  getActualMinimum(int field)
  • 获取/设置每周第一天是星期几
    int  getFirstDayOfWeek()
    void  setFirstDayOfWeek(int value)

4   

子类:GregorianCalendar类

  • 可以直接new该类对象完成日历功能的使用。
  • GregorianCalendar类扩展了Calendar类的功能,可以直接通过年月日时分秒的方式创建对象。
    GregorianCalendar()
    GregorianCalendar(int year, int month, int dayOfMonth)
    GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute)
    GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second)
  • GregorianCalendar类提供了世界上大多数历法表示方法。
  • GregorianCalendar类提供了判断闰年的方法
    boolean  isLeapYear(int year)

5  DateFormat类

(1)概述

  • FormateDemo类,该类为抽象类,但是提供了Instance方法可以实现标准样式的格式化和解析。
  • 和Calendar类类似,如需要自定义样式可以使用其子类SimpleDateFormat。

(2)字段

  • SHORT    yy-M-d 上午/下午h:mm
  • MEDIUM   yyyy-M-d h:mm:ss
  • LONG     yyyy年M月d日 上午/下午hh时mm分ss秒
  • FULL     yyyy年M月d日 星期 上午/下午hh时mm分ss秒 CST
  • (3)方法
  • 按指定标准样式初始化DateFormat对象
    static DateFormat    getInstance();           // 默认风格SHORT
    static DateFormat    getDateInstance();       // 默认风格MEDIUM
    static DateFormat    getTimeInstance();       // 默认风格MEDIUM
    static DateFormat    getDateTimeInstance();   // 默认风格MEDIUM
  • 将日期对象按指定标准样式转化为字符串
    String    format(Date date);
  • 将字符串按指定标准样式解析为日期对象
    Date    parse(String source);

 

6 示例

  1. Date date = new Date(1391234567891l);

  2. // 指定标准样式

  3. DateFormat dateStaFormat = DateFormat.getDateTimeInstance(DateFormat. LONG, DateFormat.MEDIUM );

  4. String date_Sta_str = dateStaFormat.format(date ); // 格式化,2014年2月1日 14:02:47

  5.  
  6. String dateTime = "2014年11月15日 14:16:50";

  7. try {

  8. Date nowDateTime = dateStaFormat.parse(dateTime ); // 解析,Sat Nov 15 14:16:50 CST 2014

  9. long millisTime = nowDateTime.getTime(); // 1416032210000

  10. } catch (ParseException e) {

  11. e.printStackTrace();

  12. }


 

7   SimpleDateFormat类

(1) 概述

  • SimpleDateFormat类是DateFormat的子类,和Calendar类似,DateFormat类通过工厂方法获得的对象就是SimpleDateFormat类对象。
  • SimpleDateFormat类可以按指定样式创建对象,可以自定义日期时间的格式。
  • 3. 构造器

    SimpleDateFormat()
    SimpleDateFormat(String pattern)
    SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
    SimpleDateFormat(String pattern, Locale locale)

     

    4. 常用方法

    更换指定样式
    void  applyPattern(String pattern)

     

    5. 示例

     
  • Date date = new Date(1391234567891l);

  • // 指定样式

  • SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd 'at' HH:mm:ss.SSS" );

  • String date_str = dateFormat.format( date); // 格式化,2014/02/01 at 14:02:47.891

  •  
  • dateFormat.applyPattern("yyyy.MM.dd" ); // 更换样式

  • String dateTime = "2014.11.15";

  • try {

  • Date nowDateTime = dateFormat.parse( dateTime); // 解析,Sat Nov 15 00:00:00 CST 2014

  • } catch (ParseException e) {

  • e.printStackTrace();

  • }

  • 8 Date,Calendar和DateFormat的关系

  • 1. Date和Calendar可以相互转换。

    2. Date和DateFormat配合格式化和解析。

    3. 也就是说Date可以作为桥梁存在。

    4. 示例

     
  • package date;

  •  
  • import java.text.DateFormat;

  • import java.text.ParseException;

  • import java.util.Calendar;

  • import java.util.Date;

  •  
  •  
  • public class GregorianCalendarDemo {

  •  
  • public static void main(String[] args) throws ParseException {

  • Date date = new Date();

  • Calendar cal = Calendar.getInstance();

  • DateFormat df = DateFormat.getInstance();

  •  
  • // 1. Date <-> Calendar

  • Calendar date2cal = Calendar.getInstance();

  • date2cal.setTime( date);

  • Date cal2date = cal.getTime();

  •  
  • // 2. Date <-> DateFormat

  • String time = df.format(date); // "14-12-16 下午11:47"

  • Date df2date = df.parse( time); // Tue Dec 16 23:48:00 CST 2014

  • }

  • }

  • 案例

    1. 时间转换和简单计算

     
  • package date;

  • import java.text.DateFormat;

  • import java.text.ParseException;

  • import java.text.SimpleDateFormat;

  • import java.util.Calendar;

  • import java.util.Date;

  •  
  • public class DateText {

  •  
  • public static void main(String[] args) {

  • /*

  • * 1. 将毫秒时间转换为指定日期格式: xxxx年x月x日 h:m:s

  • * 2. "2014/11/11"转成日期对象。

  • * 3. "2014-11-11"到"2015年4月29日"到底有多少天?

  • * 4. 获取给定年份到现在每年的2月有多少天?

  • */

  •  
  • // 1. 将毫秒时间转换为指定日期格式: xxxx年x月x日 h:m:s

  • Date date = new Date(1400000000000l);

  • DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat. LONG, DateFormat.MEDIUM );

  • String dateString = dateFormat.format( date);

  • System.out.println( dateString);

  •  
  • // 2. "2014/11/11"转成日期对象。

  • SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy/MM/dd" );

  • try {

  • date = sDateFormat.parse( "2014/11/11");

  • System.out.println( date);

  • } catch (ParseException e) {

  • System.out.println( "解析错误!" );

  • e.printStackTrace();

  • }

  •  
  • // 3. "2014-11-11"到"2015年4月29日"到底有多少天?

  • String dateString1 = "2014-11-11";

  • String dateString2 = "2015年4月29日" ;

  • int dateStyle1 = DateFormat. MEDIUM;

  • int dateStyle2 = DateFormat. LONG;

  • int days;

  • try {

  • days = calculateDays(dateString1 , dateStyle1 , dateString2, dateStyle2 );

  • System.out.println( dateString1 + " 到 " + dateString2 + " 间有 " + days + " 天" );

  • } catch (ParseException e) {

  • System.out.println( "解析错误!" );

  • e.printStackTrace();

  • }

  •  
  • // 4. 获取给定年份到现在每年的2月有多少天,最后一天星期几?

  • int year = 1989;

  • int endYear = Calendar.getInstance().get(Calendar. YEAR);

  • for (; year <= endYear; year++) {

  • show(year );

  • }

  •  
  • }

  • public static void show(int year) {

  • Calendar cal = Calendar.getInstance();

  • cal.set(year, 2, 1);

  • cal.add(Calendar. DAY_OF_MONTH, -1);

  • System.out.println( year + "年 二月包含 " + cal.get(Calendar.DAY_OF_MONTH) + " 天,最后一天是 "

  • + getDayInWeek(cal .get(Calendar.DAY_OF_WEEK)));

  • }

  •  
  • public static String getDayInWeek(int dayOfWeek) {

  • if (dayOfWeek < 1 || dayOfWeek > 7) {

  • throw new RuntimeException( dayOfWeek + " : 没有对应的星期!" );

  • }

  • String[] week = {"", "星期日", "星期一" , "星期二 " , "星期三" , "星期四" , "星期五 " , "星期六" };

  • return week[ dayOfWeek];

  • }

  •  
  • public static int calculateDays(String dateString1, int dateStyle1, String dateString2 ,

  • int dateStyle2) throws ParseException {

  • long dateMillis1 = DateFormat.getDateInstance(dateStyle1).parse( dateString1).getTime();

  • long dateMillis2 = DateFormat.getDateInstance(dateStyle2).parse( dateString2).getTime();

  • long margin = Math.abs(dateMillis1 - dateMillis2 );

  • return ( int) ( margin/1000/60/60/24);

  • }

  • }


  •  

    2. 打印当月的日历,今天用*标注

     
  • package date;

  •  
  • import java.text.DateFormatSymbols;

  • import java.util.Calendar;

  •  
  • public class CalendarTest {

  •  
  • public static void main(String[] args) {

  • // 打印当月的日历

  • Calendar cal = Calendar.getInstance();

  •  
  • // 获取今天日期和月份

  • int today = cal.get(Calendar. DAY_OF_MONTH);

  • int month = cal.get(Calendar. MONTH);

  •  
  • // 将日历指向本月第一天

  • cal.set(Calendar. DAY_OF_MONTH, 1);

  •  
  • // 本月第一天是星期几,以及一周的第一天是星期几

  • int weekday = cal.get(Calendar. DAY_OF_WEEK);

  • int firstDayOfWeek = cal.getFirstDayOfWeek();

  •  
  • // 判断日历第一行第一列是哪一天

  • int daysInLastMonth = 0;

  • while ( weekday != firstDayOfWeek) {

  • // 如果本月第一天不是一周的第一天,那么日历指向前一天

  • daysInLastMonth++;

  • cal.add(Calendar. DAY_OF_MONTH, -1);

  • weekday = cal.get(Calendar. DAY_OF_WEEK);

  • }

  •  
  • // 打印星期名

  • String[] weekdayName = new DateFormatSymbols().getWeekdays();

  • do {

  • System.out.printf( "%6s", weekdayName [weekday ]);

  • cal.add(Calendar. DAY_OF_MONTH, 1);

  • weekday = cal.get(Calendar. DAY_OF_WEEK);

  • } while ( weekday != firstDayOfWeek);

  • System.out.println();

  •  
  • // 打印第一行属于上个月日期的空格

  • for (int i = 0; i < daysInLastMonth; i++) {

  • System.out.print( " " );

  • }

  •  
  • // 打印日期

  • cal.set(Calendar. DAY_OF_MONTH, 1);

  • while ( month == cal.get(Calendar. MONTH)) {

  • int day = cal.get(Calendar. DAY_OF_MONTH);

  • System.out.printf( "%5d", day );

  •  
  • // 如果是今天,则打印*

  • if (day == today) {

  • System. out.print("*" );

  • } else {

  • System. out.print(" " );

  • }

  •  
  • // 日历步进

  • cal.add(Calendar. DAY_OF_MONTH, 1);

  • weekday = cal.get(Calendar. DAY_OF_WEEK);

  •  
  • // 如果一行结束,加入换行符

  • if (weekday == firstDayOfWeek) {

  • System. out.println();

  • }

  • }

  •  
  • // 如果该月结束不在一行的末尾,则加入一换行符

  • if (weekday != firstDayOfWeek) {

  • System.out.println();

  • }

  • }

  • }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值