主要内容:
1、StringBuffer的使用。
2、正则表达式、大数操作、日期格式化、Random类的使用。
3、System、Runtime、Process、Math、Calendar类的使用。
4、反射机制在程序中的应用。
一丶StringBuffer。
1、StringBuffer的简介。
String表示一个字符串的操作,但是String本身有如下特点:
两种声明的方式,而且比较的时候靠equals()比较内容。
一个字符串的内容声明之后则不可改变。
当字符串的内容需要被改变的时候就使用StringBuffer。
在String中如果要想完成两个字符串的连接,依靠"+"。
但是在StringBuffer类中要想完成连接则需要使用的是append()方法。
此方法被重载过多次,而且每个方法返回类型都是StringBuffer:
public StringBuffer append(char c)。
根据这种返回类型的特性,可以采用代码链的形式,例如:StringBuffer对象.append().append()。
范例
:进行字符串的连接。
package org.study.RebortChao;
public class StringBufferDemo01 {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer();
buf.append("hello"); //增加内容
buf.append("world").append("!!!");
System.out.println(buf);
}
}/*hello world !!!*/
如果现在需要将一个StringBuffer的类型变成String的话:
必须依靠 toString()方法完成。
String和StringBuffer不能够直接转换的。
package org.study.RebortChao;
public class StringBufferDemo02{
public static void main(String[] args) {
StringBuffer buf = new StringBuffer();
buf.append("hello"); //增加内容
buf.append(" world").append("!!!");
String str = buf.toString() ; //StringBuffer --> String
System.out.println(str);
}
}
StringBuffer的内容是允许改变的:
所以在进行引用传递的时候,可以将方法中对StringBuffer操作的结果返回。
package org.study.RebortChao;
public class StringBufferDemo03{
public static void main(String[] args) {
StringBuffer buf=new StringBuffer();
buf.append("hello"); //增加内容
buf.append("world").append("!!!");
fun(buf);
System.out.println(buf);
}
public static void fun(StringBuffer temp){
temp.append("\n").append(1).append(" + ").append(2).append(" = ").append(1 + 2);
}
}
/*从程序中的最终结果来看,StringBuffer的内容是完全允许改变的。*/
2、StringBuffer的应用。
需要经常【改变字符串的内容】要使用StringBuffer。
【内容不需要随时改变】的话,使用String就够了。
范例:
以下情况下就必须使用StringBuffer
package org.study.RebortChao;
public class StringBufferDemo04 {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer();
for (int x = 0; x < 1000; x++) {
buf.append(x);
}
System.out.println(buf);
}
}
3、StringBuffer的方法。
StringBuffer本身也是一个类,有着许多的方法,大多同String一样。
但是StringBuffer也有着属于自己的方法。
①、字符串的反转。
public StringBuffer reverse()
package org.study.RebortChao;
public class ReverseDemo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer();
buf.append("hello world!!!");
System.out.println(buf.reverse());//调用reverse反转函数
}
}
②、字符串的替换。
在String类中依靠replaceAll()方法完成替换
public StringBuffer replace(int start,int end,String str)
需要指定替换的开始和结束位置
package org.study.RebortChao;
public class ReplaceDemo{
public static void main(String[] args){
StringBuffer buf = new StringBuffer();
buf.append("hello world!!!");
System.out.println(buf.replace(0, buf.length(), "XXX"));//从0开始到最后都将被XXX所取代。
}
}
③、插入内容
append()采用顺序的方式依次连接到后面的位置。
可以使用insert()方法完成在指定位置上的增加:
public StringBuffer insert(int offset,char c)
此方法被重载过很多次,可以插入各种数据类型。
package org.study.RebortChao;
public class InsertDemo{
public static void main(String[] args) {
StringBuffer buf = new StringBuffer();
buf.append("world!!!").insert(0, "hello");
//从0的位置开始插入
System.out.println(buf);
}
}
二丶Runtime-表示的是运行时的状态对象。
每当有一个JVM进程产生的时候都会自动生成一个被私有化的Runtime类的对象。
那么一旦构造方法被私有化,则内部一定会存在一个方法,可以取得本类的实例化对象:
public static Runtime getRuntime()。
只要没有发现构造方法,则构造方法一定被私有化了,属于【单例设计】,则此时一定可以从类的内部找到一个static 方法,取得本类的实例。
Runtime run = Runtime.getRuntime() ;
Runtime类可以取得一些系统的信息或者是建立一个新的进程。
1、取得系统的信息。
总共可以使用的内存:public long totalMemory();
取得最大可用的内存:public long maxMemory();
取得当前空余的内存:public long freeMemory();
范例:
观察系统的内存的使用情况。
package org.study.RebortChao;
public class RuntimeDemo01{
public static void main(String[] args){
Runtime run = Runtime.getRuntime();
System.out.println("** 1、maxMemory:" + run.maxMemory());
System.out.println("** 1、totalMemory:" + run.totalMemory());
System.out.println("** 1、freeMemory:" + run.freeMemory());
String str = "";
for (int x = 0; x < 10000; x++) { // 将产生大量的垃圾
str += x;
}
System.out.println("========= 产生垃圾之后 ============");
System.out.println("** 2、maxMemory:" + run.maxMemory());
System.out.println("** 2、totalMemory:" + run.totalMemory());
System.out.println("** 2、freeMemory:" + run.freeMemory());
}
}
/*for循环产生大量的垃圾,freeMemory()的空间明显减少。*/
垃圾的回收。
package org.study.RebortChao;
public class RuntimeDemo02 {
public static void main(String[] args) {
Runtime run = Runtime.getRuntime();
System.out.println("========= 产生垃圾之前 ============");
System.out.println("** 1、maxMemory:" + run.maxMemory());
System.out.println("** 1、totalMemory:" + run.totalMemory());
System.out.println("** 1、freeMemory:" + run.freeMemory());
String str = "";
for (int x = 0; x < 10000; x++) { //将产生大量的垃圾
str += x;
}
System.out.println("========= 产生垃圾之后 ============");
System.out.println("** 2、maxMemory:" + run.maxMemory());
System.out.println("** 2、totalMemory:" + run.totalMemory());
System.out.println("** 2、freeMemory:" + run.freeMemory());
run.gc() ; //垃圾收集
System.out.println("========= 垃圾收集之后 ============");
System.out.println("** 2、maxMemory:" + run.maxMemory());
System.out.println("** 2、totalMemory:" + run.totalMemory());
System.out.println("** 2、freeMemory:" + run.freeMemory());
}
}
2、运行本机程序。
public Process exec(String command) throws IOException
此方法返回一个Process类的对象实例,那么此类可以用于进程的控制。
销毁进程:public void destroy()
范例:
执行程序notepad.exe。
package org.study.RebortChao;
public class RuntimeDemo03{
public static void main(String[] args) throws Exception {
Runtime run = Runtime.getRuntime();
Process pro = run.exec("notepad.exe"); //运行程序
Thread.sleep(2000); //延时2秒。
pro.destroy();
}
}
三丶System类
System.out.println();
System是一个类。
out是一个静态属性。
println()是out对象所提供的一个方法。
1、取得计算的时间
①、System类本身可以取得一个系统的当前时间,只是返回的时候按照long返回。
取得当前时间的方法:public static long currentTimeMillis()
package org.study.RebortChao;
public class SystemDemo01{
public static void main(String[] args) {
long start = System.currentTimeMillis();
String str = "";
for (int x = 0; x < 10000; x++) { // 将产生大量的垃圾
str += x;
}
long end = System.currentTimeMillis();
System.out.println("花费的时间:"+(end - start));
}
}
2、垃圾回收与对象生命周期
public static void gc()。
当调用此方法的时候实际上就等同于调用了Runtime类中提供的gc()方法,两个是一样的。
方法:protected void finalize() throws Throwable
当一个对象被回收之前都会默认调用此方法,但是此方法上抛出的异常是 Throwable。Throwable 表示 Error 和Exception,证明此方法有可能产生错误或者是异常,但是此方法的好处即便是产生了问题也不会影响程序的执行。一般一个对象都要经历以下的生命周期:
加载-->【初始化】-->【使用】-->【回收】-->卸载
范例:
观察对象的回收。
package org.study.RebortChao;
class Person {
public Person(){
System.out.println("我出生了。。。");
}
@Override
protected void finalize() throws Throwable {
System.out.println("我完了,我被回收了。。。");
}
}
public class ObjectGCDemo {
public static void main(String[] args) {
Person per = new Person();
per = null;
System.gc(); //手工回收
}
}
四丶math类-数学的操作类。
1、常用值与函数:
Math.PI 记录的圆周率
Math.E 记录e的常量
2、Math中还有一些类似的常量,都是一些工程数学常用量。
Math.abs求绝对值 .
Math.sin正弦函数Math.asin反正弦函数 .
Math.cos余弦函数 Math.acos反余弦函数 .
Math.tan正切函数 Math.atan反正切函数Math.atan2商的反正切函数 .
Math.toDegrees弧度转化为角度Math.toRadians角度转化为弧度 .
Math.ceil得到不小于某数的最大整数 .
Math.floor得到不大于某数的最大整数 .
Math.IEEEremainder求余 .
Math.max求两数中最大 .
Math.min求两数中最小 .
Math.sqrt求开方 .
Math.pow求某数的任意次方, 抛出ArithmeticException处理溢出异常 .
Math.exp求e的任意次方 .
Math.log10以10为底的对数 .
Math.log自然对数 .
Math.rint求距离某数最近的整数(可能比某数大,也可能比它小).
Math.round同上,返回int型或者long型(上一个函数返回double型) .
Math.random返回0,1之间的一个随机数.
五丶大数操作类。
1、大整数操作类BigInteger
package org.study.RebortChao;
import java.math.BigInteger;
public class BigIntegerDemo{
public static void main(String[] args) {
BigInteger bi1 = new BigInteger(Long.MAX_VALUE + "");
BigInteger bi2 = new BigInteger(Long.MAX_VALUE + "");
System.out.println("加法:"+bi1.add(bi2));
System.out.println("减法:"+bi1.subtract(bi2));
System.out.println("乘法:"+bi1.multiply(bi2));
System.out.println("除法:");
BigInteger res[]=bi1.divideAndRemainder(new BigInteger("333"));
System.out.println("整数部分:" + res[0]);
System.out.println("小数部分:" + res[1]);
}
}
2、大小数操作类:BigDecimal
package org.study.RebortChao;
import java.math.BigDecimal;
public class BigDecimalDemo {
public static void main(String[] args) {
BigDecimal bd1 = new BigDecimal(Double.MAX_VALUE);
BigDecimal bd2 = new BigDecimal(Double.MAX_VALUE);
System.out.println("加法:"+bd1.add(bd2));
System.out.println("减法:"+bd1.subtract(bd2));
System.out.println("乘法:"+bd1.multiply(bd2));
System.out.println("除法:"+bd1.divide(bd2));
}
}
在BigDecimal类中除法操作可以指定小数的保留位数:
public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)
范例:
四舍五入操作
package org.study.RebortChao;
import java.math.BigDecimal;
class MyMathRound{
public static double round(double num, int scale){
BigDecimal bd = new BigDecimal(num);
return bd.divide(new BigDecimal(1),scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static BigDecimal round(String num, int scale){
BigDecimal bd = new BigDecimal(num);
return bd.divide(new BigDecimal(1), scale, BigDecimal.ROUND_HALF_UP);
}
}
public class RoundDemo{
public static void main(String[] args){
System.out.println("四舍五入:" + MyMathRound.round(98.56137, 2));
System.out.println("四舍五入:" + MyMathRound.round(98.56637, 2));
System.out.println("四舍五入:" + MyMathRound.round("98.56637", 2));
}
}
六丶随机数
在java.util.Random类中主要的功能是用于产生随机数的。
范例:
产生10个数字,都不大于100
package org.study.RebortChao;
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
Random rand = new Random();
for (int x = 0; x < 10; x++) {
System.out.println(rand.nextInt(100));
}
}
}
七丶日期操作。
1、Date类
java.util.Date类是一个专门取得日期的操作类,直接实例化对象输出即可。
package org.study.RebortChao;
import java.util.Date;
public class DateDemo{
public static void main(String[] args) {
System.out.println(new Date());
}
}
输出的时间信息是:
Sat Dec 02 15:03:17 CST 2017
/*确实是取得了一个日期,但是日期的格式并不符合日常习惯。*/
2、Calendar类
Calendar类是采用手工的方式取得日期,可以通过此类精确到毫秒。
此类的定义如下:
public abstract class Calendar extends Object
implements Serializable, Cloneable, Comparable<Calendar>
这个类本身是一个抽象类,抽象类要想实例化肯定使用子类:GregorianCalendar
package org.study.RebortChao;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarDemo{
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar();
System.out.println("YEAR:"+calendar.get(Calendar.YEAR));
System.out.println("MONTH:"+(calendar.get(Calendar.MONTH) + 1));
System.out.println("DATE:"+calendar.get(Calendar.DATE));
System.out.println("HOUR_OF_DAY:"+calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE:"+calendar.get(Calendar.MINUTE));
System.out.println("SECOND:"+calendar.get(Calendar.SECOND));
System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
}
}
设计如下的一个接口:
package org.study.RebortChao;
public interface DateTime{
/**
* 取得日期
* @return 日期的字符串,例如:2009-12-22
*/
public String getDate() ;
/**
* 取得日期时间
* @return 日期时间的字符串,例如:2009-12-22 11:06:23.345
*/
public String getDateTime() ;
/**
* 取得时间戳
* @return 返回时间戳的字符串,例如:20091222110623345
*/
public String getTimeStamp() ;
}
前面需要补0的问题需要注意,例如:01。
package org.study.RebortChao;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class DateTimeImpl implements DateTime {
private Calendar calendar;
public DateTimeImpl() {
this.calendar = new GregorianCalendar();
}
@Override
public String getDate() {
StringBuffer buf = new StringBuffer();
buf.append(calendar.get(Calendar.YEAR)).append("-");
buf.append(this.addZero((calendar.get(Calendar.MONTH) + 1), 2)).append("-");
buf.append(this.addZero(calendar.get(Calendar.DATE), 2));
return buf.toString();
}
@Override
public String getDateTime() {
StringBuffer buf = new StringBuffer();
buf.append(calendar.get(Calendar.YEAR)).append("-");
buf.append(this.addZero((calendar.get(Calendar.MONTH) + 1), 2)).append("-");
buf.append(this.addZero(calendar.get(Calendar.DATE), 2)).append(" ");
buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2)).append(":") ;
buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)).append(":") ;
buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)).append(".") ;
buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3)) ;
return buf.toString();
}
@Override
public String getTimeStamp() {
StringBuffer buf = new StringBuffer();
buf.append(calendar.get(Calendar.YEAR));
buf.append(this.addZero((calendar.get(Calendar.MONTH) + 1), 2));
buf.append(this.addZero(calendar.get(Calendar.DATE), 2));
buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY), 2));
buf.append(this.addZero(calendar.get(Calendar.MINUTE), 2)) ;
buf.append(this.addZero(calendar.get(Calendar.SECOND), 2)) ;
buf.append(this.addZero(calendar.get(Calendar.MILLISECOND), 3)) ;
return buf.toString();
}
private String addZero(int num, int len) {
StringBuffer buf = new StringBuffer();
buf.append(num);
while (buf.length() < len) {
buf.insert(0, 0);
}
return buf.toString();
}
}
3、SimpleDateFormat类
依靠SimpleDateFormat可以成完成String和Date型数据的转换。
日期的格式化: java.text.SimpleDateFormat 类
格式化日期的模板:
年yyyy、月MM、日dd、时HH、分mm、秒ss、毫秒SSS
范例:
格式化日期。
package org.study.RebortChao;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo{
public static void main(String[] args){
//准备好了一个要格式化的模板
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = new Date();
String str = sdf.format(date);
System.out.println("格式化后的日期:"+str);
}
}
通过SimpleDateFormat类可以将一个Date型的数据变为String型的数据。
范例:
将String变回Date型
package org.study.RebortChao;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo02{
public static void main(String[] args) throws Exception {
String str = "2009-12-24 11:51:57.500" ;
// 准备好了一个要格式化的模板
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdf.parse(str) ; // 将String --> Date
System.out.println("格式化后的日期:" + date);
}
}
SimpleDateFormat类还可以完成日期格式的转换。
package org.study.RebortChao;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo03{
public static void main(String[] args) throws Exception{
String oldDate = "2009-12-24 11:51:57.500";
String newDate = null;
// 准备好了一个要格式化的模板
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat sdf2 = new SimpleDateFormat(
"yyyy年MM月dd日HH时mm分ss秒SSS毫秒");
Date date = sdf1.parse(oldDate);
//从原日期字符串中取出日期数字
newDate = sdf2.format(date);
//新的日期格式
System.out.println("格式化后的日期:" + newDate);
}
}
DateTime接口的实现类通过SimpleDateFormat类完成应该是最方便的。
package org.study.RebortChao;
import java.text.SimpleDateFormat;
public class DateTimeImpl implements DateTime {
private SimpleDateFormat sdf;
@Override
public String getDate() {
String str = null;
this.sdf = new SimpleDateFormat("yyyy-MM-dd");
str = this.sdf.format(new java.util.Date());
return str;
}
@Override
public String getDateTime() {
String str = null;
this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
str = this.sdf.format(new java.util.Date());
return str;
}
@Override
public String getTimeStamp() {
String str = null;
this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
str = this.sdf.format(new java.util.Date());
return str;
}
}
八丶Arrays类-数组的操作类。
import java.util.Arrays;
①、实现对数组的从小到大的排序:Arrays.sort(a);
②、数组元素的定位查找find=Arrays.binarySearch(a,8);
· //括号中前面的a为你将要查询的数组名称,8为想要查询的数字。
· //find的值为查询的数字在数组中的下标。
③、String aString =Arrays.toString(a);
// String前的a和括号中的a均表示数组名称。
System.out.println(aString);//String前的a表示数组名称。
④、boolean b=Arrays.asList(a).contains(1);
System.out.println(b);//注意:b的值只可能是true或false
九丶比较器。
两种比较接口的区别:
Comparable属于定义类的时候使用,而Comparator属于挽救的比较器,所在的包不同。
Comparable只有一个方法,而Comparator有两个方法。
1、Comparable接口
Comparable接口主要是用于执行比较器操作的接口,定义如下:
public interface Comparable<T>{
public int compareTo(T o);
}
Comparable接口中仅有一个compareTo()方法,此方法返回一个int型的数据,此值会返回三种结果:
①、0:两个对象相等。②、1:大于。③、-1:小于
如果对象数组要排序,则对象所在的类必须现实现Comparable接口。
/*如果要使用Arrays.sort()进行排序的话,则肯定要在对象所在的类中进行编写比较器的操作。*/
package org.study.RebortChao;
import java.util.Arrays;
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "姓名:" + this.name + ",年龄:" + this.age;
}
@Override
public int compareTo(Person o) {
if(this.age > o.age) {
return 1;
}else if(this.age < o.age) {
return -1;
}else{
return 0;
}
}
}
public class SortObjectArray{
public static void main(String[] args) {
Person per[] = {new Person("张三", 20), new Person("李四", 19),new Person("王五", 23)};
Arrays.sort(per);
for (int x = 0; x < per.length; x++) {
System.out.println(per[x]);
}
}
}
Comparable排序的原理实际上就属于BinaryTree(二叉树)排序的形式。
范例:
package org.study.RebortChao;
class BinaryTree{
class Node {
private Comparable data;
private Node left; //保存左子树
private Node right; //保存右子树
public Node(Comparable data){
this.data = data;
}
public void addNode(Node newNode){
if(this.data.compareTo(newNode.data)>= 0){ //放在左子树
if(this.left == null){
this.left = newNode;
}else{
this.left.addNode(newNode);
}
}
if(this.data.compareTo(newNode.data) < 0) { //放在右子树
if(this.right == null) {
this.right = newNode;
}else{
this.right.addNode(newNode);
}
}
}
public void printNode(){ //左-根-右
if(this.left != null){
this.left.printNode();
}
System.out.println(this.data);
if(this.right != null){
this.right.printNode();
}
}
}
private Node root; //根节点
public void add(Comparable data){
Node newNode = new Node(data);
if(this.root == null){
this.root = newNode;
}else{
this.root.addNode(newNode);
}
}
public void print(){
if(this.root != null){
this.root.printNode();
}
}
}
public class BinaryTreeDemo{
public static void main(String[] args){
BinaryTree bt = new BinaryTree();
bt.add("B");
bt.add("A");
bt.add("C");
bt.print();
}
}
2、Comparator
一个封装好的类可以通过Comparator挽救一个排序的规则。
package org.study.RebortChao;
import java.util.Comparator;
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
if(o1.getAge() > o2.getAge()) {
return -1;
}else if(o1.getAge() < o2.getAge()) {
return 1;
}else{
return 0;
}
}
}
之后就可以继续使用Arrays类提供的sort()方法进行排序。
package org.study.RebortChao;
import java.util.Arrays;
public class Demo{
public static void main(String[] args){
Person per[] = { new Person("张三", 20), new Person("李四", 19),
new Person("王五", 23) };
Arrays.sort(per, new PersonComparator());
for(int x = 0; x < per.length; x++) {
System.out.println(per[x]);
}
}
}
十丶正则表达式。
十一丶反射机制。
十二丶对象克隆
克隆就是将一个对象直接复制。
一个类的对象要完成对象的克隆操作的话,则必须实现一个接口:Cloneable。
且必须依靠Object类中的clone()方法:
protected Object clone() throws CloneNotSupportedException
此方法属于受保护的访问权限,所以如果一个非本包的非子类,要访问肯定不能访问。
package org.study.RebortChao;
class Person implements Cloneable{
private String name ;
public Person(String name){
this.name = name ;
}
public void setName(String name){
this.name = name ;
}
public String getName(){
return this.name ;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class CloneDemo{
public static void main(String[] args) throws Exception {
Person per = new Person("张三");
Person cp = (Person) per.clone(); //克隆
System.out.println(per + "," + per.getName());
System.out.println(cp + "," + cp.getName());
}
}
/*Cloneable是一个标识接口,用于表示一种能力。*/