java高级特性:实用类

java的强大之处在于它提供了多种多样的类库。大大提高了编程效率和质量。

java.lang : java使用最广泛的类,自动导入所有程序中,最基础的类和接口、包装类、Math类、String类等常用的类都包含在此。此外,该包还提供了用于管理类的动态加载、外部进程创建、主机环境查询、安全策略实施等的系统操作类。
java.util : 包含了系统辅助类,特别是Collection、List、Set、Map等集合类。
java.io : 包含了输入流和输出流有关的类。
java.net : 包含了与网络操作有关的类。Socket、ServerSocket类等。
java.sql : 包含了与数据库相关的类。Connection、Statement类等。

枚举

枚举(enum)类型是Java 5新增的特性,它是一种新的类型,允许用常量来表示特定的数据片断,而且全部都以类型安全的形式来表示。
枚举是一组固定的常量组成的类型,使用关键字enum定义
创建枚举类型要使用 enum 关键字,隐含了所创建的类型都是 java.lang.Enum 类的子类(java.lang.Enum 是一个抽象类)

public enum EnumTest {
    MON, TUE, WED, THU, FRI, SAT, SUN;
}

enum对象常用方法:

int compareTo(E o) 比较此枚举与指定对象的顺序。

getDeclaringClass() 返回与此枚举常量的枚举类型相对应的 Class 对象。

String name() 返回此枚举常量的名称,在其枚举声明中对其进行声明。

int ordinal() 返回枚举常量的序数(它在枚举声明中的位置,其中初始常量序数为零)。

String toString() 返回枚举常量的名称,它包含在声明中。

valueOf(Class enumType, String name) 返回带指定名称的指定枚举类型的枚举常量。

enum中自定义函数

public enum Week  {
    MON("周一"),WED("周二"),SAT("周六"),SUN("周日");
    private String weekend;
    private Week(String weekend){
        this.weekend=weekend;
    }
    public String getWeekend(){
        double i=4.0d;
        return this.weekend;
    }
}
public class WeekDemo {

    public void dowhat(Week day){
        switch (day) {
        case MON:
        case WED:
            System.out.println(Week.MON.getWeekend()+"\t努力写代码");
            break;
        case SAT:
            System.out.println("休息日,去看场电影吧");
            break;
        case SUN:
            System.out.println(Week.SUN.getWeekend()+"\t休息日,去打篮球吧");
            break;
        default:
            System.out.println("让你输入的是地球上的星期,小伙,你输入的是什么玩意");
            break;
        }
    }
    public static void main(String[] args) {
        WeekDemo we=new WeekDemo();
        we.dowhat(Week.MON);
        Week sat=Week.SUN;
        we.dowhat(sat);

    }
}

enum 的语法结构尽管和 class的语法不一样,但是经过编译器编译之后产生的是一个class文件。该class文件经过反编译可以看到实际上是生成了一个类,该类继承了java.lang.Enum

可以把 enum 看成是一个普通的 class,它们都可以定义一些属性和方法,不同之处是:enum 不能使用 extends关键字继承其他类,因为 enum 已经继承了 java.lang.Enum(java是单一继承)。

枚举构造为私有的,定义方法必须在变量后加上 “ ; ”。 switch支持枚举类型。

包装类

包装类和基本数据类型关系
包装类作为基本数据类型对应的类型存在,方便对象的操作。
包装类包含每种基本数据类型的相关属性,以及相关操作方法。

自动装箱和自动拆箱:
java中有自动把基本数据类型转化为包装类称为自动装箱。
自动把包装类转化为基本数据类型称为自动拆箱。
需要注意的是:

Integer的自动装箱和拆箱。
在-128-127之间的数:
    Integer  i1=100 ;
    Integer  i2=100 ;
    i1==i2(true)
在-128217之外的数:
    Integer  i3=200 ;
    Integer  i4=200 ;
    i3==i4(false)

若自动装箱的值在-127-127之间,对象引用不变。
若自动装箱的值超过127,则新建对象。

Double  d1=100.0
Double  d2=100.0
Double  d3=200.0
Double  d4=200.0
System.out.println(d1==d2);//false
System.out.println(d3==d4);//fasle

Boolean b1=true;
Boolean b3=true;
Boolean b2=false;
Boolean b4=false;
System.out.println(b1==b3);//true
System.out.println(b1==b2);//false
System.out.println(b2==b4);//true

Integer a=1;
int i=1;
int j=900;
Integer b=2;
Integer c=3;
Integer d=3;
Integer e=321;
Integer f=321;
Long g=3L;
Long h=2L;
System.out.println(c==d);//true
System.out.println(e==f);//fasle
System.out.println(g==(h+1));//true
System.out.println(g==(a+b));//true
System.out.println(a==i);//true
System.out.println(a.equals(i));//true
System.out.println(a==j);//false
System.out.println(a.equals(j));//false

Double 类型不管传入的参数是多少值都会new出一个对象来表达该数值

Integer、Short、Byte、Characer、Long、的valueof方法实现类似,而Double和Float比较特殊,每次都返回新包装对象。

Math类和Random类

Math:算数类   
    Math.random();生成0.0-1.0之间随机数。
Random:随机数类
    Math.random();其实是调用Random.nextDouble();
    两个方法都返回0.0-1.0之间的浮点数;不包含1.0。
    Math不需要实例化。Math中的所有的类都由static修饰,可以直接访问方法。
    Math.random()*10之后就会生成0-10之间的浮点数......以此类推;
    Random()必须实例化。Random.nextDouble();也会产生0.0-1.0之间的浮点数。
    要取0-10之间的数。与之前方法一致。

Math类常用方法:

public class MathClassOftenMethod {
    /**
     * Math类常用方法
     * Math.PI 记录的圆周率 
       Math.E 记录e的常量 
       Math中还有一些类似的常量,都是一些工程数学常用量。
       Math.abs 求绝对值 
       Math.sin 正弦函数 Math.asin 反正弦函数 
       Math.cos 余弦函数 Math.acos 反余弦函数 
       Math.tan 正切函数 Math.atan 反正切函数 Math.atan2 商的反正切函数 
       Math.toDegrees 弧度转化为角度 Math.toRadians 角度转化为弧度 
       Math.IEEEremainder 求余 
       Math.sqrt 求开方 
       Math.pow 求某数的任意次方, 抛出ArithmeticException处理溢出异常 
       Math.exp 求e的任意次方 
       Math.log10 以10为底的对数 
       Math.log 自然对数 
     */
    public static void main(String[] args) {
        /*  
         * abs()
         * abs求绝对值
         */
        System.out.println(Math.abs(3.2)); // 3.2
        System.out.println(Math.abs(-3.2)); // 3.2
        /*
         * ceil()
         * ceil天花板的意思,传入一个double值然后返回较大的值,其余位数不舍弃。
         */
        System.out.println(Math.ceil(2.1)); // 3.0
        System.out.println(Math.ceil(-2.1)); // -2.0
        System.out.println(Math.ceil(0.0)); // 0.0
        System.out.println(Math.ceil(-0.0)); // -0.0
        /*
         * floor()
         * floor是地板的意思,传入一个double值然后返回较小的值,其余位置不舍弃
         */
        System.out.println(Math.floor(-10.1)); // -11.0
        System.out.println(Math.floor(10.7)); // 10.0
        System.out.println(Math.floor(-0.7)); // -1.0
        System.out.println(Math.floor(0.0)); // 0.0
        System.out.println(Math.floor(-0.0)); // -0.0
        /*
         * max()、min()
         * max()获取两个数的最大值,min()获取两个数的最小值
         */
        System.out.println(Math.max(9, 2)); // 9
        System.out.println(Math.min(6, 7)); // 6
        /* 
         * random 取得一个大于或者等于0.0小于不等于1.0的随机数  
         */
        System.out.println(Math.random());
        /*
         * rint 四舍五入,返回double值  
         * 注意.5的时候会取偶数
         */
        System.out.println(Math.rint(3.2)); // 3.0
        System.out.println(Math.rint(2.5)); // 2.0
        System.out.println(Math.rint(1.5)); // 2.0
        /*
         * round 四舍五入,返回int值,double时返回long值  
         */
        System.out.println(Math.round(3.2)); // 3
        System.out.println(Math.rint(2.5)); // 2
        System.out.println(Math.rint(1.5)); // 2    
    }
}

String StringBuffer StringBuilder

String类常用方法:

public class StringClassOftenObject {
    /**
     * String 类中的常用方法
     * ==和equals的区别
     * ==比较的是引用的内存地址
     * equals比较的是对象的值是否相同
     * equalslgnoreCase忽略大小写比较字符串
     * toLowerCase();转换为小写
     * toUpperCase();转换为大写
     * trim() 去掉起始和结尾的空格
     * split() 指定的正则表达式或者字符串拆分字符串
     */
    public static void main(String[] args) {
        String str="HelloWorld889";
        System.out.println(str.length()); //length() 获取字符串长度
        System.out.println(str.charAt(2)); //  charAt()截取一个字符串


        char ch[]=new char[4];
        str.getChars(1, 5, ch, 0); 
        // getchars(开始下标,结束下标,指定接收数组,起始下标)
        for(char i:ch){
            System.out.print(i+" \t");
        }


        System.out.println();
        byte i[]=new byte[4];
        //getBytes()转化为byte类型的字节码文件放入到一个数组中
        for(byte o:i){  
            System.out.print(o+" \t");
        }


        System.out.println();
        ch=str.toCharArray();  
         //toCharArray()把字符串截取成一个char类型的数组中
        for(char p:ch){
            System.out.print(p+" \t");
        }   

        // regionMatches(字符串中的起始位置,比较的字符串参数,字符串参数的起始位置,要比较的字符串的长度)
        System.out.println();
        System.out.println(str.regionMatches(1, "lell", 1, 3)); 

        // 忽略大小写比较两个字符串是否相等。
        System.out.println(str.regionMatches(true, 0, "h", 0, 1)); 

        // 测试字符串自否以指定字符串开始
        System.out.println(str.startsWith("H")); 

        // 测试字符串自否以指定字符串结束
        System.out.println(str.endsWith("8")); 

        System.out.println(str.indexOf("H")); // 返回字符串中指定字符开始的位置
        System.out.println(str.lastIndexOf("8")); // 返回字符串中自定字符串最后一次出现的位置。

        String p=str.substring(0); // 从指定位置截取字符串
        String p1=str.substring(0,9);  // 从指定位置到结束位置截取字符串
        System.out.println(p);
        System.out.println(p1);

        System.out.println(str.concat("988"));//连接字符串

        System.out.println(str.replace("l", "p")); // 出现指定字符时,就替换
        System.out.println(str.replace(p1, str)); // 指定字符串替代指定字符串


    }
}

StringBuffer类与StringBuilder类常用方法一致,只不过StringBuffer是线程安全的,同样肯定效率要低。StringBuilder相率最高,但线程问题需要开发者自行考虑。

public class StringBufferOftenMethod {
    public static void main(String[] args) {
        /*
         * append() 将指定数据加在容器末尾,返回值也是StringBuffer
         */
        StringBuffer str2 = new StringBuffer(896); // 创建896字节的字符缓冲区
        StringBuffer str = new StringBuffer("abc");

        StringBuffer str1 = str.append("kio");
        System.out.println(str1);
        System.out.println(str2 == str);
        /*
         * insert() 插入数据,然后形成新的字符串
         */
        System.out.println(str.insert(2, "123"));
        /*
         * delete(int start,int end) 删除指定区间字符串包含start不包含end deleteCharAt()
         * 删除指定位置的字符串,将剩余的内容组成新的字符串
         */
        System.out.println(str.deleteCharAt(1));
        /*
         * reverse() 将字符串内容反转形成新的字符串
         */
        System.out.println(str.reverse());
        /*
         * setCharAt() 修改字符串中的指定值为新的字符
         */
        str.setCharAt(3, '6');
        System.out.println(str);
        /*
         * trim() 将字符串位置缩小成和字符串一致的长度,减少空间浪费
         */
        str.trimToSize();
        System.out.println(str.length());
        /*
         * setLength() 设置字符串缓冲区大小
         */
        str.setLength(89);
        System.out.println(str.length());
        /*       * capacity() 获取字符串容量
         */
        int i = str.capacity();
        System.out.println(i + "*********");
        /*
         * ensureCapacity() 重新设置字符串的大小 现在的长度不能改变
         */
        str.ensureCapacity(896);
        System.out.println(str.length());
        /*
         * 
         */
        char q[] = new char[6];
        str.getChars(0, 5, q, 0);
        for (char w : q) {
            System.out.print(w + " \t");
        }
        /*
         * toString() 转化为String类型
         */
        System.out.println();
        str.toString();
        System.out.println(str);
    }
}

常见面试题:
String 、StringBuffer、StringBuilder对比

  1. String :字符串常量
    每次对String类型进行改变的时候都等同于生成新的String对象然后改变引用关系。所以经常改变内容的字符串最好不要用String类型。

  2. StringBuffer:字符串变量
    每次对StringBuffer进行改变时,是对StringBuffer对象本身进行操作,在字符串经常变动的情况下推荐使用StringBuffer类。

  3. StringBuilder:字符串变量
    StringBuilder和StringBuffer等价,区别在于StringBuffer是线程安全的,StringBuilder是单线程的,不提供同步。

String s1=new String("abc");
StringBuffer s2=new StringBuffer("abc");
s2.append(s1);  //abcabc
s1=s2.toString();  //abcabc
s1.concat("abc");   //对String进行操作,生成了新的String对象。需要接收才会起效。
System.out.println(s1);//abcabc

时间日期类

public class DataClassOftenMethod {
    public static void main(String[] args) {
        Date today;
        Calendar now;
        DateFormat f1,f2;
        String s1,s2;
        System.out.println("显示Date类的相关用法");
        today=new Date();
        System.out.println("new出的Date日期:"+today);


        System.out.println("\n用DateFormat类显示各种日期格式:");
        f1=DateFormat.getDateInstance();
        s1=f1.format(today);
        System.out.println("DateFormat格式化日期原始值:\t"+s1);
        f1=DateFormat.getDateInstance(DateFormat.LONG,Locale.CHINA);
        s1=f1.format(today);
        System.out.println("DateFormat格式化日期为Long型的中国日期:\t"+s1);
        f1=DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.CHINA);
        s1=f1.format(today);
        System.out.println("DateFormat格式化日期为medium型的中国日期:\t"+s1);
        f1=DateFormat.getDateInstance(DateFormat.SHORT,Locale.CHINA);
        s1=f1.format(today);
        System.out.println("DateFormat格式化日期为SHORT型的中国日期:\t"+s1);

        System.out.println("\n用DateFormat类显示各种时间格式:");
        f1 = DateFormat.getTimeInstance(); 
        s1 = f1.format(today); 
        System.out.println("DateFormat格式化时间原始值:\t"+s1);
        f1 = DateFormat.getTimeInstance(DateFormat.LONG,Locale.CHINA); 
        s1 = f1.format(today); 
        System.out.println("DateFormat格式化时间为Long型的中国时间:\t"+s1);
        f1 = DateFormat.getTimeInstance(DateFormat.MEDIUM,Locale.CHINA); 
        s1 = f1.format(today); 
        System.out.println("DateFormat格式化时间为medium型的中国时间:\t" +s1);
        f1 = DateFormat.getTimeInstance(DateFormat.SHORT,Locale.CHINA); 
        s1 = f1.format(today); 
        System.out.println("DateFormat格式化时间为SHORT型的中国时间:\t"+s1);


        System.out.println("\n显示Calendar的相关时间用法");
        now = Calendar.getInstance(); 
        today = now.getTime(); 
        System.out.println("Date类引用Calendar类的getTime方法获取的当前时间的初始值:\t"+ today.toString());
    }
}
Date:
    java.util.Date
    日期类:
    Date    date =new       Date();     //创建当前日期
    java.text.SimpleDateFormat
    日期格式转换类:
    SimpleDateFormat    sdf=new SimpleDateFormat("yyyy-MM-dd    hh:mm:ss");     
    //格式化当前日期把日期转换成字符串
    String      time=sdf.format(date);  //把日期转化为指定格式
    把字符串转换为日期
    String      sourceDate="2017-11-22      08:02:10";
    date=sdf.parse(sourceDate);

常用日期时间代码封装

public class DateSystemTimeMethod implements Serializable {
    /**
     * @Description: 得到中国当前系统时间
     * @return Timestamp
     * @author Young
     * @date 2017年12月8日
     */
    public static Timestamp getCurrentCnDateWithTimestamp() {
        Date date = new Date();
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA);
        fm.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String moditime = fm.format(date);
        Timestamp lasttime = Timestamp.valueOf(moditime); // 字符型转换为时间型。
        return lasttime;
    }

    /**
     * @Description: 得到中国系统当前时间yyyy-MM-dd HH:mm:ss 格式
     * @return String
     * @throws
     * @author Young
     * @date 2017年12月8日
     */
    public static String getCurrentCnDateWithString() {
        Date date = new Date();
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA);
        fm.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String moditime = fm.format(date);
        return moditime;
    }

    /**
     * 
     * @Description: 得到中国系统当前时间yyyy-MM-dd 格式
     * @return String
     * @throws
     * @author Young
     * @date 2017年12月8日
     */
    public static String getCurrentCnDateWithString1() {
        Date date = new Date();
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        fm.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String moditime = fm.format(date);
        return moditime;
    }

    /**
     * 
     * 
     * @Description: 得到中国系统当前时间yyyy-MM-dd 格式
     * @return String
     * @param Date
     * @author Young
     * @date 2017年12月8日
     */
    public static String getCurrentCnDateWithString1(Date d) {
        Date date = null;
        if (d != null)
            date = d;
        else
            date = new Date();
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        fm.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String moditime = fm.format(date);
        return moditime;
    }

    /**
     * 
     * 返回Date类型的中国当前系统时间
     * 
     * @Description: TODO
     * @return Date
     * @throws
     * @author Young
     * @date 2017年12月8日
     */
    public static Date getCurrentCnDateWithDate() {
        Date date = new Date();
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA);
        fm.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String moditime = fm.format(date);
        Timestamp lasttime = Timestamp.valueOf(moditime); // 字符型转换为时间型。
        return new Date(lasttime.getTime());
    }

    /**
     * 得到已知日期后相隔多久的日期。
     * 
     * @Description: TODO
     * @return Date
     * @param date日期
     *            ,amount数字,type 1:月 2:季度 3:年
     * @author Young
     * @date 2017年12月8日
     */
    public static Date getAfterDateWithDate(Date date, int amount, int type) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(date.getTime());
        if (type == 1) {
            c.add(GregorianCalendar.MONTH, amount);
        } else if (type == 2) {
            c.add(GregorianCalendar.MONTH, (amount * 3));
        } else if (type == 3) {
            c.add(GregorianCalendar.YEAR, amount);
        }
        return c.getTime();
    }

    /**
     * 
     * 得到已知日期后相隔多久的日期。
     * 
     * @Description: TODO
     * @return Timestamp
     * @param date日期
     *            ,amount数字,type 1:月 2:季度 3:年
     * @author Young
     * @date 2017年12月8日
     */
    public static Timestamp getAfterDateWithTimestamp(Date date, int amount,
            int type) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(date.getTime());
        if (type == 1) {
            c.add(GregorianCalendar.MONTH, amount);
        } else if (type == 2) {
            c.add(GregorianCalendar.MONTH, (amount * 3));
        } else if (type == 3) {
            c.add(GregorianCalendar.YEAR, amount);
        }
        return new Timestamp(c.getTimeInMillis());
    }

    /**
     * 
     * @Description: 得到当前时间的两位数年份
     * @return String
     * @author Young
     * @date 2017年12月8日
     */
    public static String getDateYY(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        if (d != null)
            c.setTime(d);
        String year = String.valueOf(c.get(Calendar.YEAR));
        year = year.substring(year.length() - 2);
        return year;
    }

    /**
     * 
     * @Description: 得到当前时间的四位数年份
     * @return String
     * @throws
     * @author Young
     * @date 2017年12月8日
     */
    public static String getDateYYYY(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        if (d != null)
            c.setTime(d);
        return String.valueOf(c.get(Calendar.YEAR));
    }

    /**
     * 
     * @Description: 得到当前时间的两位数月份
     * @return String
     * @throws
     * @author Young
     * @date 2017年12月8日
     */
    public static String getDateMM(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        if (d != null)
            c.setTime(d);
        String month = String.valueOf(c.get(Calendar.MONTH) + 1);
        if (month.length() == 1)
            month = "0" + month;
        return month;
    }

    /**
     * @Description: 得到当前时间的两位数月份中的第几日
     * @return String
     * @author Young
     * @date 2017年12月8日
     */
    public static String getDateDD(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        if (d != null)
            c.setTime(d);
        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
        if (day.length() == 1)
            day = "0" + day;
        return day;

    }

    /**
     * 
     * @Description: 得到当前时间的两位数季度
     * @return String
     * @throws
     * @author Young
     * @date 2017年12月8日
     */
    public static String getDateQQ(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        if (d != null)
            c.setTime(d);
        String q = String.valueOf(Double.valueOf(
                Math.ceil((c.get(Calendar.MONTH) + 1) / 3d)).intValue());
        if (q.length() == 1)
            q = "Q" + q;
        return q;
    }

    /**
     * @Description:得到当前时间的两位数一年中的第几周
     * @return String
     * @throws
     * @author Young
     * @date 2017年12月8日
     */
    public static String getDateWW(Date d) {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        if (d != null)
            c.setTime(d);
        String w = String.valueOf(c.get(Calendar.WEEK_OF_YEAR));
        if (w.length() == 1)
            w = "0" + w;
        return w;
    }
}
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值