zoukankan      html  css  js  c++  java
  • 常用类Math,StringBuffer,包装类,Date

    ----------- StringBuffer ---------------

    StringBuffer是字符串缓冲区。

    是一个容器。

    特点:

    1,长度是可变化的。

    2,可以直接操作多个数据类型。

    3,最终会通过toString方法变成字符串。

    C create U update R read D delete

    1,存储。

    StringBuffer append():将指定数据作为参数添加到已有数据结尾处。

    StringBuffer insert(index,数据):可以将数据插入到指定index位置。

    2,删除。

    StringBuffer delete(start,end):删除缓冲区中的数据,包含start,不包含end。

    StringBuffer deleteCharAt(index):删除指定位置的字符。

    3,获取。

    char charAt(int index)

    int indexOf(String str)

    int lastIndexOf(String str)

    int length()

    String substring(int start, int end)

    4,修改。

    StringBuffer replace(start,end,string);

    void setCharAt(int index, char ch) ;

    5,反转。

    StringBuffer reverse();

    6,

    将缓冲区中指定数据存储到指定字符数组中。

    void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

    JDK1.5 版本之后出现了StringBuilder.

    StringBuffer是线程同步。

    StringBuilder是线程不同步。

    以后开发,建议使用StringBuilder

    升级三个因素:

    1,提高效率。

    2,简化书写。

    3,提高安全性。

    package com.demo.str;
    
    public class StringBufferDemo {
        public static void main(String[] args) {
            // 创建StringBuffer可变字符串
            // 默认创建16个容量空间
            StringBuffer sb1 = new StringBuffer();
            StringBuffer sb2 = sb1.append("AAAA");
            System.out.println(sb1 == sb2); // 比较2个对像内存地址是否相同
            System.out.println(sb1.equals(sb2)); //比较2个对像内存地址是否相同
            System.out.println(sb1.toString()); // 获取StringBuffer对象值
            System.out.println("-------存储--------");
            /*1,存储。
            StringBuffer append():将指定数据作为参数添加到已有数据结尾处。
            StringBuffer insert(index,数据):可以将数据插入到指定index位置。*/
            sb1.append("BBB");
            System.out.println(sb2.toString());
            sb1.insert(4, "CCC"); // 指定插入值得偏移量
            System.out.println(sb2.toString());
    
            /*2,删除。
            StringBuffer delete(start,end):删除缓冲区中的数据,包含start,不包含end。
            StringBuffer deleteCharAt(index):删除指定位置的字符。*/
            sb1.delete(4, 7);
            System.out.println(sb1);
            String sql = "INSERT INTO T_TB VALUES (字段1,字段2,字段3,";
            StringBuffer sqlsb = new StringBuffer(sql);
            sqlsb.deleteCharAt(sql.length() - 1);
            System.out.println(sqlsb);
             
            /*4,修改。
            StringBuffer replace(start,end,string);
            void setCharAt(int index, char ch) ;*/
            sqlsb.replace(0, 11, "UPDATE"); // 选定区域更换为新的字符串
            System.out.println(sqlsb);
            sqlsb.setCharAt(1, 'A'); // 替换指定索引某个字符
            System.out.println(sqlsb);
    
            /*5,反转。(倒序输出)
            StringBuffer reverse();*/
            StringBuffer sb3 = new StringBuffer("FFFKDKDFJFJSJDJ");
            sb3.reverse();
            System.out.println(sb3);
        }
    }

    效率测试

    package com.demo.str;
    
    /**
     * 测试String,StringBuffer效率
     * StringBuffer和StringBuilder区别:
     * StringBuffer是线程安全的,StringBuilder是非线程安全
     * 
     * 
     * @author Administrator
     *
     */
    public class TestFunction {
        public static void main(String[] args) {
            testString();
            //testStringBuffer();
        }
        
        // 字符串拼接比较多情况下效率非常高
        private static void testStringBuffer() { // 4
            StringBuffer sb = new StringBuffer("AAA");
            // 记录当前开始的时间
            long startTime = System.currentTimeMillis();
            for (int i = 1 ; i <=50000; i++) {
                sb.append("BBB");
            }
            long endTime = System.currentTimeMillis();
            System.out.println("StringBuffer用时:"+ (endTime - startTime));
        }
    
        
        private static void testString() { // 3292
            String str = "AAA";
            // 记录当前开始的时间
            long startTime = System.currentTimeMillis();
            for (int i = 1 ; i <=50000; i++) {
                str+="BBB";
                System.out.println(str);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("String用时:"+ (endTime - startTime));
            
        }
    }

    ------------ 包装类 --------------------------

    //包装类,每一个基本类型都有对应的包装类,

    //并且都有一个将基本类型创建成包装类的构造方法。

    Boolean bobj = new Boolean(true);

    Integer iobj = new Integer(1);

    Long lobj = new Long(1);

    Short sobj = new Short((short) 1);

    Character cobj = new Character('a');

    Float fobj = new Float(1.0f);

    Double dobj = new Double(1.0);

    Byte byobj = new Byte((byte) 1);

    //每个包装类都有一个valueOf()方法,用于将字符串转成相应的包相类

    System.out.println(Boolean.valueOf("false"));

    System.out.println(Integer.valueOf("1"));

    System.out.println(Short.valueOf("1"));

    System.out.println(Long.valueOf("1"));

    System.out.println(Float.valueOf("1.0"));

    System.out.println(Double.valueOf("1.0"));

    System.out.println(Byte.valueOf("1"));

    //Character类是构造将基本类型char转成包装类型Character

    System.out.println(Character.valueOf('a'));

    //第个包装类都有一个parseXxx方法,将字符串转成对应的基本类型,除Character类

    System.out.println(Boolean.parseBoolean("false"));

    System.out.println(Integer.parseInt("1"));

    System.out.println(Short.parseShort("1"));

    System.out.println(Long.parseLong("1"));

    System.out.println(Float.parseFloat("1.0"));

    System.out.println(Double.parseDouble("1.0"));

    System.out.println(Byte.parseByte("1"));

    //Character包装类的常用方法

    Character.isLetter('a');//判断这个字符是否为英文字母

    Character.isDigit('1');//判断这个字符是否为数字

    Character.isUpperCase('A');//判断这个字符是否为大写

    Character.isLowerCase('a');//判断这个字符是否为小写

    Character.isWhitespace(' ');//判断这个字符是否为空格或回车

    package com.demo.encapsulation;
    
    /**
     * 包装类
     * @author Administrator
     *
     */
    public class EncapsulationDemo {
        public static void main(String[] args) {
            // byte  short  char       int     long   float   double  boolean
            // Byte  Short  Character  Integer Long   Float   Double  Boolean 
            // 对象的默认为都为null
            // 把一个基本数据类型转换为一个包装类
            int number = 100;
            Integer integer1 = new Integer(number);
            Integer integer2 = 20; // boxing 装箱 (new Integer(20))
            // 可以通过xxxValueOf这个方法
            Long ln = Long.valueOf(30L);
            
            // 把一个包装类转换为一个基本数据类型 xxxValue
            Short size1 = new Short((short) 20);
            short size2 = size1.shortValue();
            int num = integer1.intValue();
            
            // 强制转换的方法parseXxx -> 基本数据类型
            byte b = Byte.parseByte("22");
            
            // 把一个字符串安装对应进制转换为十进制的数输出
            int result = Integer.parseInt("110",8);
            System.out.println(result);
            
            //Character包装类的常用方法
            Character.isLetter('a');//判断这个字符是否为英文字母
            Character.isDigit('1');//判断这个字符是否为数字
            Character.isUpperCase('A');//判断这个字符是否为大写
            Character.isLowerCase('a');//判断这个字符是否为小写
            Character.isWhitespace(' ');//判断这个字符是否为空格或回车
            
            // 如果你定义的变量是基本数据类型, 就是parseXxx方法
            // 如果你定义的变量是包装数据类型, 就使用xxxValueOf方法
        }
    
    }

    --------------- Math -----------------------------

    //取整,返回小于目标函数的最大整数,如下将会返回-2

    Math.floor(-1.8);

    //取整,返回发育目标数的最小整数

    Math.ceil()

    //四舍五入取整

    Math.round()

    //计算平方根

    Math.sqrt()

    //计算立方根

    Math.cbrt()

    //返回欧拉数e的n次幂

    Math.exp(3);

    //计算乘方,下面是计算3的2次方

    Math.pow(3,2);

    //计算自然对数

    Math.log();

    //计算绝对值

    Math.abs();

    //计算最大值

    Math.max(2.3,4.5);

    //计算最小值

    Math.min(,);

    //返回一个伪随机数,该数大于等于0.0并且小于1.0

    Math.random

    Random类专门用于生成一个伪随机数,它有两个构造器:一个构造器使用默认的种子(以当前时间作为种子),另一个构造器需要程序员显示的传入一个long型整数的种子。 

    Random比Math的random()方法提供了更多的方式来生成各种伪随机数。

    e.g

    public class RandomTest {
        public static void main(String[] args) {
        // TODO Auto-generated method stub
        Random rand = new Random();
        System.out.println("随机布尔数" + rand.nextBoolean());
        byte[] buffer = new byte[16];
        rand.nextBytes(buffer);
        //生产一个含有16个数组元素的随机数数组
        System.out.println(Arrays.toString(buffer));
    
        System.out.println("rand.nextDouble()" + rand.nextDouble());
    
        System.out.println("Float浮点数" + rand.nextFloat());
    
        System.out.println("rand.nextGaussian" + rand.nextGaussian());
    
        System.out.println("" + rand.nextInt());
    
        //生产一个0~32之间的随机整数
        System.out.println("rand.nextInt(32)" + rand.nextInt(32));
    
        System.out.println("rand.nextLong" + rand.nextLong());
        }
    } 

    为了避免两个Random对象产生相同的数字序列,通常推荐使用当前时间作为Random对象的种子,代码如下:

    Random rand = new Random(System.currentTimeMillis());

    在 java7 中引入了ThreadLocalRandom

    在多线程的情况下使用ThreadLocalRandom的方式与使用Random基本类似,如下程序·片段示范了ThreadLocalRandom的用法:

    首先使用current()产生随机序列之后使用nextCXxx()来产生想要的伪随机序列 :

    ThreadLocalRandom trand= ThreadLocalRandom.current();

    int val = rand.nextInt(4,64);

    1

    2

    产生4~64之间的伪随机数

    package com.demo.math;
    
    import java.util.Random;
    import java.util.UUID;
    import java.util.concurrent.ThreadLocalRandom;
    
    public class MathDemo {
        public static void main(String[] args) {
            
            // 静态方法不需要创建对象的实例, 直接通过类名.方法调用
            // 取绝对值
            System.out.println(Math.abs(-20));
            // 向上取整
            System.out.println(Math.ceil(33.3));
            // 向下取整
            System.out.println(Math.floor(33.1));
            // 四舍五入
            System.out.println(Math.round(3.6));
            // 取0-1之间随机数
            System.out.println(Math.random()); // [0, 1) 随机小数
            System.out.println((int)Math.ceil(Math.random()*100000));
            
            // 产生随机的对象
            Random rd = new Random(); // [0,1]
            System.out.println(rd.nextInt(33)  + 1); // 1 - 33
            // 产生一个随机的字符串
            System.out.println(UUID.randomUUID());
            // jdk7 版本引入新对象(线程安全的随机)
            ThreadLocalRandom trand= ThreadLocalRandom.current();
            int val = trand.nextInt(1,2);
            System.out.println(val);
            
            // 取一个数的多次幂
            System.out.println(Math.pow(2, 3));
            // 取某个数的平方根
            System.out.println(Math.sqrt(3));
        }
    }

    ----------------- Date -------------------------

    new Date(long time);

    getTime();

    package com.demo.date;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class DateDemo {
        public static void main(String[] args) throws ParseException {
            // 创建一个日期对象
            Date date = new Date();
            System.out.println(date);
            // 把日期对象转换为毫秒值
            System.out.println(date.getTime());
            // 把一个毫秒值转换为一个时间
            System.out.println(new Date(10100101010L));
            /**
             * 字母  日期或时间元素  表示  示例  
                G  Era 标志符  Text  AD  
                y  年  Year  1996; 96  
                M  年中的月份  Month  July; Jul; 07  
                w  年中的周数  Number  27  
                W  月份中的周数  Number  2  
                D  年中的天数  Number  189  
                d  月份中的天数  Number  10  
                F  月份中的星期  Number  2  
                E  星期中的天数  Text  Tuesday; Tue  
                a  Am/pm 标记  Text  PM  
                H  一天中的小时数(0-23)  Number  0  
                k  一天中的小时数(1-24)  Number  24  
                K  am/pm 中的小时数(0-11)  Number  0  
                h  am/pm 中的小时数(1-12)  Number  12  
                m  小时中的分钟数  Number  30  
                s  分钟中的秒数  Number  55  
                S  毫秒数  Number  978  
                z  时区  General time zone  Pacific Standard Time; PST; GMT-08:00  
                Z  时区  RFC 822 time zone  -0800  
             */
            // 年-月-日 转换时间的格式
            SimpleDateFormat sdf = new SimpleDateFormat();
            // 设置时间格式
            sdf.applyPattern("yyyy年M月");
            // 把一个Date对象转换为一个指定格式的字符串
            System.out.println(sdf.format(date));
            
            // 把一个时间字符串转换为一个日期对象
            sdf.applyPattern("yyyy-M-dd");
            Date date2 = sdf.parse("2019-2-30");
            System.out.println(date2);
        }
    
    }

    ---------------- Calendar ------------------------

    Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。瞬间可用毫秒值来表示,它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量。

    例:

    Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。

    cal.add(Calendar.DAY_OF_MONTH, -1);//取当前日期的前一天.

    cal.add(Calendar.DAY_OF_MONTH, +1);//取当前日期的后一天.

    //通过格式化输出日期 

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    System.out.println("Today is:"+format.format(Calendar.getInstance().getTime()));

    System.out.println("yesterday is:"+format.format(cal.getTime()));

    得到2007-12-25日期:

    Calendar calendar = new GregorianCalendar(2007, 11, 25,0,0,0);

    Date date = calendar.getTime();

    System.out.println("2007 Christmas is:"+format.format(date));

    java月份是从0-11,月份设置时要减1.

    GregorianCalendar构造方法参数依次为:年,月-1,日,时,分,秒.

    取日期的部分:

    int year =calendar.get(Calendar.YEAR);

    int month=calendar.get(Calendar.MONTH)+1;

    int day =calendar.get(Calendar.DAY_OF_MONTH);

    int hour =calendar.get(Calendar.HOUR_OF_DAY);

    int minute =calendar.get(Calendar.MINUTE);

    int seconds =calendar.get(Calendar.SECOND);

    取月份要加1.

    判断当前月份的最大天数:

    Calendar cal = Calendar.getInstance();

    int day=cal.getActualMaximum(Calendar.DAY_OF_MONTH);

    System.out.println(day);


    2.java.util.Date

    java.util.Date today=new java.util.Date();

    System.out.println("Today is "+formats.format(today));

    取当月的第一天:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-01");

    java.util.Date firstDay=new java.util.Date();

    System.out.println("the month first day is "+formats.format(firstDay));

    取当月的最后一天:

    Calendar cal = Calendar.getInstance();

    int maxDay=cals.getActualMaximum(Calendar.DAY_OF_MONTH);

    Format formatter3=new SimpleDateFormat("yyyy-MM-"+maxDay);

    System.out.println(formatter3.format(cal.getTime()));

    求两个日期之间相隔的天数:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    java.util.Date beginDate= format.parse("2007-12-24");

    java.util.Date endDate= format.parse("2007-12-25");

    long day=(date.getTime()-mydate.getTime())/(24*60*60*1000);

    System.out.println("相隔的天数="+day);

    一年前的日期:

    Format formatter=new SimpleDateFormat("yyyy-MM-dd");

    Date todayDate=new Date();

    long beforeTime=(todayDate.getTime()/1000)-60*60*24*365;

    todayDate.setTime(beforeTime*1000);

    String beforeDate=formatter.format(todayDate);

    System.out.println(beforeDate);

    一年后的日期:

    Format formatter=new SimpleDateFormat("yyyy-MM-dd");

    Date todayDate=new Date();

    long afterTime=(todayDate.getTime()/1000)+60*60*24*365;

    todayDate.setTime(afterTime*1000);

    String afterDate=formatter.format(todayDate);

    System.out.println(afterDate);

    求10小时后的时间

    Calendar Cal=Calendar.getInstance();

    Cal.setTime(dateOper);

    Cal.add(Calendar.HOUR_OF_DAY,10);

    System.out.println("date:"+forma.format(Cal.getTime()));

    求10小时前的时间

    Calendar Cal=Calendar.getInstance();

    Cal.setTime(dateOper);

    Cal.add(Calendar.HOUR_OF_DAY,-10);

    System.out.println("date:"+forma.format(Cal.getTime()));

    3.java.sql.Date

    继承自java.util.Date,是操作数据库用的日期类型

    Date sqlDate = new Date(Date.valueOf("2007-12-25").getTime());

    日期比较:简单的比较可以以字符串的形式直接比较,也可使用

    Date.valueOf("2007-03-08").compareTo(jDate.valueOf("2007-03-18"))方式来比较日期的大小.也可使用Date.after(Date)来比较.

    相差时间: 

    long difference=c2.getTimeInMillis()-c1.getTimeInMillis(); 

    相差天数:long day=difference/(3600*24*1000)

    相差小时:long hour=difference/(3600*1000)

    相差分钟:long minute=difference/(60*1000)

    相差秒: long second=difference/1000

    补充:

    DateFormat df=new SimpleDateFormat("yyyy-MM-dd EE hh:mm:ss");

    System.out.println(df.format(new Date()));

    Date date = new Date();

    DateFormat shortDate=DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);

    DateFormat mediumDate =DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);

    DateFormat longDate =DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);

    DateFormat fullDate =DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);

    system.out.println(shortDate.format(date));

    System.out.println(mediumDate.format(date));

    System.out.println(longDate.format(date));

    System.out.println(fullDate.format(date));

    08-4-15 下午3:24

    2008-4-15 15:24:31

    2008年4月15日 下午03时24分31秒

    2008年4月15日 星期二 下午03时24分31秒CST


    Calendar c = Calendar.getInstance();

    c.add(Calendar.MONTH, 1); // 目前時間加1個月

    System.out.println(df.format(c.getTime()));

    c.add(Calendar.HOUR, 3); // 目前時間加3小時

    System.out.println(df.format(c.getTime()));

    c.add(Calendar.YEAR, -2); // 目前時間減2年

    System.out.println(df.format(c.getTime()));

    c.add(Calendar.DAY_OF_WEEK, 7); // 目前的時間加7天

    System.out.println(df.format(c.getTime()));

    package com.demo.calendar;
    
    import java.util.Calendar;
    
    /**
     * 日历对象
     * @author Administrator
     *
     */
    public class CalendarDemo {
        public static void main(String[] args) {
            // 创建一个日历对象
            Calendar calendar = Calendar.getInstance();
            // 获取毫秒
            System.out.println(calendar.getTimeInMillis());
            // 转换为Date对象
            System.out.println(calendar.getTime());
            // 获取年,月,日, 时,分,秒,毫秒
            System.out.println(calendar.get(Calendar.YEAR));
            // 月是从0开始
            System.out.println(calendar.get(Calendar.MONTH) + 1);
            System.out.println(calendar.get(Calendar.DATE));
            System.out.println(calendar.get(Calendar.HOUR));
            System.out.println(calendar.get(Calendar.MINUTE));
            System.out.println(calendar.get(Calendar.SECOND));
            System.out.println(calendar.get(Calendar.MILLISECOND));
            // 使用set方法
            calendar.set(Calendar.YEAR, 200);
            calendar.set(Calendar.MONTH, 2);
            System.out.println(calendar);
            //////////////////// 设置这个年2月1日
            // 2018 是否是瑞年
            calendar.set(Calendar.YEAR, 2016);
            calendar.set(Calendar.MONTH, 1);
            System.out.println(calendar.getTime());
            // 查看这个月有多少天
            System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            // 使用add方法
            calendar.add(Calendar.MONTH, -3);
            System.out.println(calendar.getTime());
            System.out.println("-----------------------");
            // 比较日期 compareTo
            Calendar cl1 = Calendar.getInstance();
            cl1.add(Calendar.MONTH, -1);
            Calendar cl2 = Calendar.getInstance();
            //  return (thisTime > t) ? 1 : (thisTime == t) ? 0 : -1;
            long time = cl1.compareTo(cl2);
            System.out.println(time);
        }
    }

    -------------- System类 ----------------------

    System类

    java.lang.Object

    ——java.lang.System

    public final class System extends Object

    System 类包含一些有用的类字段和方法。*它不能被实例化。

    在 System 类提供的设施中,有标准输入、标准输出和错误输出流;对外部定义的属性和环境变量的访问;

    加载文件和库的方法;还有快速复制数组的一部分的实用方法。

    public static final InputStream in()

    “标准”输入流。此流已打开并准备提供输入数据。

    通常,此流对应于键盘输入或者由主机环境或用户指定的另一个输入源。

    public static final PrintStream out()

    “标准”输出流。此流已打开并准备接受输出数据。

    通常,此流对应于显示器输出或者由主机环境或用户指定的另一个输出目标。

    对于简单独立的 Java 应用程序,编写一行输出数据的典型方式是:

    System.out.println(data)

    public static void gc()

    运行垃圾回收器。

    调用 gc 方法暗示着 Java 虚拟机做了一些努力来回收未用对象,以便能够快速地重用这些对象当前占用的内存。

    当控制权从方法调用中返回时,虚拟机已经尽最大努力从所有丢弃的对象中回收了空间。

    调用 System.gc() 实际上等效于调用:

    Runtime.getRuntime().gc()

    在Object类中

    protected void finalize()

    当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。

    子类重写 finalize 方法,以配置系统资源或执行其他清除。

    public static void exit(int status)

    终止当前正在运行的 Java 虚拟机。

    参数用作状态码;

    根据惯例,非 0 的状态码表示异常终止。

    该方法调用 Runtime 类中的 exit 方法。该方法永远不会正常返回。

    调用 System.exit(n) 实际上等效于调用:

    Runtime.getRuntime().exit(n)

    public static long currentTimeMillis()

    返回以毫秒为单位的当前时间。

    注意,当返回值的时间单位是毫秒时,值的粒度取决于底层操作系统,并且粒度可能更大。

    例如,许多操作系统以几十毫秒为单位测量时间。

    返回:

    当前时间与协调世界时 1970 年 1 月 1 日午夜之间的时间差(以毫秒为单位测量)。

    public static void arraycopy(Object src,int srcPos, Object dest,int destPos,int length)

    从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。

    参数:

    src - 源数组。

    srcPos - 源数组中的起始位置。

    dest - 目标数组。

    destPos - 目标数据中的起始位置。

    length - 要复制的数组元素的数量。

    package com.demo.sys;
    
    import java.util.Arrays;
    import java.util.Scanner;
    
    /**
     * System
     * @author Administrator
     *
     */
    public class SystemDemo {
        public static void main(String[] args) {
            System.out.println("输出流");
            // System.exit(0); // 0 代表正常退出, 非0的数都是非正常退出
            // 创建一个扫描器对象
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入你的名字:");
            //System.err.println(sc.nextLine());
            sc.close();
            // gc 显示调用垃圾回收器
            System.gc();
            // 返回当前毫秒值
            System.out.println(System.currentTimeMillis());
            // 获取系统中属性
            System.out.println(System.getProperty("java.io.tmpdir"));
            // arraycopy (数组拷贝)[数组类型必须完全一致,只能是基本数据类型的数组]
            /*否则,只要下列任何情况为真,则抛出 ArrayStoreException 异常并且不会修改目标数组: 
    
            src 参数指的是非数组对象。 
            dest 参数指的是非数组对象。 
            src 参数和 dest 参数指的是那些其组件类型为不同基本类型的数组。 
            src 参数指的是具有基本组件类型的数组且 dest 参数指的是具有引用组件类型的数组。 
            src 参数指的是具有引用组件类型的数组且 dest 参数指的是具有基本组件类型的数组。 */
    
            // 只能存储同类的元素
            double[] numbers = new double[]{1,2,35,22,2,4};
            // 定义一个数组
            double[] numbers1 = new double[10];
            System.arraycopy(numbers, 0, numbers1, 0, 6);
            System.out.println(Arrays.toString(numbers1));
        }
    }

    ----------------------------- Runtime 类 ---------------------------

    Runtime 类代表着Java程序的运行时环境,每个Java程序都有一个Runtime实例,

    该类会被自动创建,我们可以通过Runtime.getRuntime() 方法来获取当前程序的Runtime实例。

    获取当前Jvm的内存信息

    /*
    * 获取当前jvm的内存信息,返回的值是 字节为单位
    * */
    public static void getFreeMemory() {
        //获取可用内存
        long value = Runtime.getRuntime().freeMemory();
        System.out.println("可用内存为:"+value/1024/1024+"mb");
        //获取jvm的总数量,该值会不断的变化
        long totalMemory = Runtime.getRuntime().totalMemory();
        System.out.println("全部内存为:"+totalMemory/1024/1024+"mb");
        //获取jvm 可以最大使用的内存数量,如果没有被限制 返回 Long.MAX_VALUE;
        long maxMemory = Runtime.getRuntime().maxMemory();
        System.out.println("可用最大内存为:"+maxMemory/1024/1024+"mb");
    }
    
    获取jvm可用的处理器核心的数量
    /*
    * 获取jvm可用的处理器核心的数量
    * */
    public static void getAvailableProcessors() {
        int value = Runtime.getRuntime().availableProcessors();
        System.out.println(value);
    }
    
    执行系统命令
    public static void commend() {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("calc");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    package com.demo.runtime;
    
    import java.io.IOException;
    
    public class RuntimeDemo {
        
        public static void getFreeMemory() {
            //获取可用内存
            long value = Runtime.getRuntime().freeMemory();
            System.out.println("可用内存为:"+value/1024/1024+"mb");
            //获取jvm的总数量,该值会不断的变化
            long  totalMemory = Runtime.getRuntime().totalMemory();
            System.out.println("全部内存为:"+totalMemory/1024/1024+"mb");
            //获取jvm 可以最大使用的内存数量,如果没有被限制 返回 Long.MAX_VALUE;
            long maxMemory = Runtime.getRuntime().maxMemory();
            System.out.println("可用最大内存为:"+maxMemory/1024/1024+"mb");
        }
        
        public static void main(String[] args) throws IOException {
            Runtime run = Runtime.getRuntime();
            // Process proc = run.exec("mspaint");
            // 获取内存信息
            getFreeMemory();
            // 获取可用核心数量
            System.out.println(run.availableProcessors());
        }
    }

     反射

    package com.demo;
    
    /**
     * 学生类
     * @author Administrator
     *
     */
    public class Student {
        
        static { // Student.class文件首次加载到jvm上面的时候才执行
            System.out.println("Student.class文件被加载到jvm");
        }
        
        private String name;
        private String sex;
        private Integer age;
        
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        
        
    
    }
    package com.demo;
    
    public class TestStudent extends Student {
        
        static {
            System.out.println("=========");
        }
        
        public static void main(String[] args) {
            // javac编译期:把.java文件编译为.class文件
            // java 运行期:把.class文件加载到jvm
            /*Student student = new Student(); // 加载到jvm上面,并在内存中创建一个student对应类对象
            Class clazz = student.getClass();*/
            Class clazz = TestStudent.class;
            System.out.println(clazz.getSuperclass());
            // student student=new student.这有实例化对象名。反射过来的实例化对象有名字吗?
        }
    
    }
  • 相关阅读:
    Linux部署golang程序(无数据库访问)
    MySQL备份数据库mysqldump
    Linux命令netstat
    SQL优化01(转载)
    springcloud之gateway点滴
    关于数据库错误:serverTimeZone
    代码重构的重要性
    关于集合的泛型
    python 视频下载神器(you-get)
    linux下ssh
  • 原文地址:https://www.cnblogs.com/sunBinary/p/10465624.html
Copyright © 2011-2022 走看看