Android之JAVASe基础篇-面向对象-常用类库(八)

来源:互联网 发布:mac芒果tv怎么缓存 编辑:程序博客网 时间:2024/05/11 22:51

一、StringBuffer和String区别。
StringBuffer是使用缓冲区的,本身也是操作字符串的,但是与String类不同,String类的内容一旦声明之后则不可改变,改变的只是其内存地址的指向,而StringBuffer中的内容是可以改变的。
对于StringBuffer而言,本身是一个具体的操作类,所以不能像String那样采用直接赋值的方式进行对象的实例化,必须通过构造方法完成。
StringBuffer中有的方法:
1.append():完成字符串的添加
2.insert(int offset,boolean b):在任意位置处为StringBuffer添加内容
3.字符串反转操作。 String str=buf.reverse().toString();//内容反转后变为String类型
4.字符串的截取:String类型字符串只能使用substring来截取大道删除效果,而StringBuffer的内容是可以用delete()方法来删除指定位置的字符串。
例子:

public class StringBufferDmeo{    public static void main(String[] args)throws Exception{        StringBuffer buf=new StringBuffer();        buf.append("hello"+'\t').append("World!"+'\n');        System.out.println("第一个StringBuffer字符串:"+buf);        buf.replace(6,11,"LIUHUAN");        System.out.println("第二个StringBuffer字符串:"+buf);        String str=buf.delete(6,15).toString();//删除指定位置,并且转为String        System.out.println("删除之后的结果:"+str);    }}

5.查找指定内容是否存在。使用 indexOf()方法查找。
6.应用:如果代码需要频繁修改字符串中的内容,则要需要使用StringBuffer了。大家记住就好了。
例子:

public class StringBufferDmeo{    public static void main(String[] args)throws Exception{        StringBuffer buf1=new StringBuffer();        buf1.append("LIUHUA");        for(int i=0;i<10;i++){            buf1.append(i);            System.out.println(buf1);        }        System.out.println(buf1);    }}

总结:如果代码需要频繁修改字符串中的内容,则要需要使用StringBuffer了,大家记住就好了。
StringBuffer中有String类中所没有的,包括delete(),insert()等等,需要的时候看doc文档就好了。
二、Runtime类
常用的方法:
getRuntime() 取得Runtime类的实例
freeMemory() 返回Java虚拟机中的空闲内存量
maxMemory() 返回JVM的最大内存量
gc() 运行垃圾回收器,释放空间
exec(String command) throws IOException 执行本机命令
大家用的时候再去查找doc吧。
三、System类
System类是一些与系统相关的属性和方法的集合,而且在System类中所有的属性
都是静态的,所以要用的时候直接使用System类直接调用即可。
常用方法:
public static void exit(int status) 系统退出,如果status为非0就表示退出
public static void gc() 垃圾回收
public static long currentTimeMillis() 返回以毫秒为单位的当前时间
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) 数组拷贝
public static Properties getProperties() 取得当前的系统全部属性
public static String getProperty(String key) 根据键值取得属性的具体内容

public class SystemDmeo{    public static void main(String[] args)throws Exception{        long startTime=System.currentTimeMillis();  //当前时间        int sum=0;        for(int i=0;i<300000000;i++){            sum +=i;        }        long endTime=System.currentTimeMillis();//计算后的时间        System.out.println("计算所花费的时间:"+(endTime-startTime)+"毫秒");    }}

四、日期操作类(Date、Calendar)
1.简单的取得日期

import java.util.*;public class DateDemo{    public static void main(String[] args)throws Exception{        Date date=new Date();        System.out.println(date);   //输出的日期: Thu Dec 31 10:53:52 GMT+08:00 2015    }}

使用SimpleDateFormat类格式化日期

import java.util.*;import java.text.*;public class DateDemo{    public static void main(String[] args)throws Exception{        //获取当前系统时间再格式化        Date date=new Date();        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        String time=format.format(date);        System.out.println(time);    }}

五、Math类和Random类
1.Math类–数学操作
查找doc文档即可
注意:Math.round(33.6); //四舍五入实际上是将小数点之后的内容全部忽略掉。
要进行精确的四舍五入的话则需要使用 BigDecimal ,有需求的时候再去用吧

2.Random类–随机数操作
查找doc文档即可
3.UUID.randomUUID() 随机数,在文件,图片重新命名的时候用到。
例子:下面是上传文件的部分代码,对UUID.randomUUID()的应用。

@RequestMapping("/addQuestion")    public int addQuestion(Question question,MultipartFile picture) throws Exception{        int status;        IAddQuestion addQuestion = new AddQuestionImple();        //得到照片原始名称        String originalFilename=picture.getOriginalFilename();        //上传图片,不为空的时候执行 防止数组越界        if(picture != null && originalFilename != null && originalFilename.length()>0){            //存储图片的物理路径            String picture_path = "";            //新图片名称:随机数+原来的图片的后缀名            String newFileName=UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));            //新图片            File newFile = new File(picture_path+newFileName);            //将内容中的图片写入磁盘            picture.transferTo(newFile);            //将新的额图片名称写到questionVo类中,最终写到数据库中。            question.setPicture(newFileName);        }        status = addQuestion.addQuestion(question);        return status;    }

六、NumberFormat
1.使用NumberFormat类进行本地化的数字显示
格式化数字

import java.util.*;import java.text.*;public class NumberFormatDmeo{    public static void main(String[] args)throws Exception{        NumberFormat nf=null;        nf=NumberFormat.getInstance();        System.out.println(nf.format(10000000));        System.out.println(nf.format(10000.345));    }}

2.使用DecimalFormat指定格式化模板
指定模版,输出就是模版的格式
格式

class FormatDmeo{        public void format(String pattern,double value){            DecimalFormat df=new DecimalFormat(pattern);            String str=df.format(value);            System.out.println("使用"+pattern+"格式化数字"+value+"的结果:"+str);        }    }    @Test    public void dateTest(){        FormatDmeo demo=new FormatDmeo();        demo.format("###,###.###", 11133333.123);        demo.format("000,000.000", 11133333.123);        demo.format("###,###.###¥", 11133333.123);        demo.format("000,000.000¥", 11133333.123);        demo.format("##.###%", 0.0345667);        demo.format("0.###%", 0.0345667);        demo.format("###.###\u2030", 0.0345667);    }

七、大数据操作
1.BigInteger操作大整数
2.BigDecimal指定小数的保留位数
BigDecimal完成大的小数操作,而且也可以使用该类进行精确的四舍五入,在开发中经常使用。
开发中很少遇到大数字的情况,一般用long 就解决了。
使用BigDecimal可以指定四舍五入的精确位置。
八、对象克隆技术
直接上例子,大家看看就行了。

class Person implements Cloneable{        private String name;        public Person(String name){            this.name=name;        }        public Object clone() throws CloneNotSupportedException{            return super.clone();        }        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }    }    @Test    public void dateTest() throws CloneNotSupportedException{        Person p1=new Person("刘欢");        Person p2=(Person) p1.clone();        p2.setName("张学良");        System.out.println("原始对象:"+p1.getName());        System.out.println("克隆之后的对象:"+p2.getName());    }

九、Arrays数组
常用的方法:
public staitc boolean equals(int[] a,int[] a2) 判断两个数组是否相等,此方法可被重载多次,可以判断各种数据类型的数组
public static void fill(int[] a,int val) 将指定内容填充到数组之中,可重载,可填充各种数据类型的数组
public static void sort(int[] a ) 数组排序,此方法可重载,可以对各种数据类型的数组进行排序
public static int binarySearch(int[] a,int key) 对排序后的数组进行检索,可以对各种类型的数组进行搜索
public static String toString(int[] a) 输出数组信息,此方法可被重载,可输出各种数据类型的数组

public void dateTest() throws CloneNotSupportedException{        int[] temp={3,4,5,6,7,12,4,3};        Arrays.sort(temp);        System.out.print("排序后的数组:");        System.out.println(Arrays.toString(temp));        //若要使用二分法查询的话,则必须是排序之后的数组        int point=Arrays.binarySearch(temp, 3);        System.out.println("元素3的位置是:"+point);        //会将10分配给数组中的每个元素        Arrays.fill(temp, 10);        System.out.print("数组填充后:");        System.out.println(Arrays.toString(temp));    }

十、Comparable和Comparator
使用中尽量使用Comparable在需要排序的类上实现好此接口。
掌握一点:只要是对象排序,则在java中永远是以Comparable接口为准的。
Comparable的格式

class Student implements Comparable<Student>{        private String name;        private int age;        private float score;        public Student(String name,int age,float score){            this.name=name;            this.age=age;            this.score=score;        }        public String toString(){            return name+"\t"+this.age+"\t"+this.score;        }        public int compareTo(Student stu){            if(this.score>stu.score){                return -1;            }else{                if(this.age>stu.age){                    return 1;                }else if(this.age<stu.age){                    return -1;                }else{                    return 0;                }            }        }    }    @Test    public void dateTest() throws CloneNotSupportedException{        Student[] stu={new Student("刘欢",20,90.0f),new Student("李四",22,100.0f),new Student("王五",19,90.9f)};        Arrays.sort(stu);        for(int i=0;i<stu.length;i++){            System.out.println(stu[i]);        }    }

十一、正则表达式
1.Pattern类和Matcher类的使用
常用正则
描述
2.String对正则的支持
开发中常常用String的正则支持
String正则支持

public void dateTest() {        String str1="A1B22C333D444E5555F".replaceAll("\\d", "_");//把数字替换成”_“        boolean temp="2015-12-31".matches("\\d{4}-\\d{2}-\\d{2}");//验证日期格式        String s[]="A1B22C333D4444E55555F".split("\\d+");//按数字split        System.out.println("字符串替换操作:"+str1);        System.out.println("字符串验证:"+temp);        System.out.print("字符串拆分:");        for(int x=0;x<s.length;x++){            System.out.println(s[x]+"\t");        }    }

十二、定时调度
TimerTask:在web开发中有可能会用到。

class MyTask extends TimerTask{        public void run(){            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");            System.out.println("时间:"+sdf.format(new Date()));        }    }    @Test    public void timeTest(){        Timer t=new Timer();        MyTask mytask=new MyTask();        t.schedule(mytask, 1000, 2000);//1s后任务执行,每3s重复    }
0 0
原创粉丝点击