6、Java 常用类库

1. StringBuffer类

String的内容一旦声明则不可改变,如果要改变,则改变的肯定是String的引用地址,那么如果现在的情况是一个字符串要被经常改变,此时就必须使用StringBuffer类,通过append()方法进行字符串的连接。

常见用法如下所示:

public StringBuffer() //StringBuffer构造方法
public StringBuffer append(char c)
public StringBuffer append(String str)
public StringBuffer append(StringBuffer sb)//追加内容
public int indexof(String str)//查找指定字符串是否存在
public int indexof(String str,int fromIndex)//指定位置处查找字符串存在
public StringBuffer insert(int offset,String str)//指定位置加上指定字符串
public StringBuffer reverse()//将内容反转保存
public StringBuffer replace(int start,int end,String str)//指定内容替换
public int length() //求出内容长度
public StringBuffer delete(int start,int end)//删除指定范围的字符串
public String substring(int start)//字符串截取,指定开始点
public String substring(int start,int end)
public String toString() //将内容转换成String类型

2. Runtime类

在Java中Runtime类表示运行时操作类,是一个封装了JVM进程的类,每一个JVM都对应着一个Runtime类的实例,此实例由JVM运行时为其实例化。Runtime类本身的构造方法是私有化(单例设计),如果想取得一个Runtime实例,则只能通过以下方式:

Runtime run=Runtime.getRuntime();

也就是说在Runtime类中提供了一个静态的getRuntime()方法,此类可以取得Runtime类的实例,那么取得Runtime类的实例由什么用处呢?既然Runtime表示的是每一个JVM实例,所以可以通过Runtime取得一些系统信息。

public static Runtime getRuntime() //取得Runtime类的实例
public long freeMemory()//取得Java虚拟机的空闲内存
public long maxMemory()//返回JVM的最大内存量
public void gc()//运行垃圾回收器,释放空间
public Process exec(String command) throws IOException//执行本机命令

3. System类

System类是一些与系统相关属性和方法的集合,而且在System类中所有的属性都是静态的,要想引用这些属性和方法,直接使用System类调用即可,下面是常用的方法:

java
public static void exit(int status)//系统退出,如果status非0表示退出
public static void gc() //运行垃圾收集机制,调用Runtime
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)//根据键值取得属性的具体内容

4. Math类

Math类是数学操作类,提供了一系列的数学操作方法,包括求绝对值,三角函数等,在Math类中提供的一切方法都是静态方法,所以直接由类名调用即可。

//Math类常见用法
Math.sqrt(9.0)
Math.max(10,30)
Math.min(10,30)
Math.pow(2,3)
Math.round(33.6)//四舍五入

5. Random类

Random类是随机数产生类,可以指定一个随机数的访问,然后任意产生在此范围中的数字。具体方法如下:

public boolean nextBoolean() //随机生成booleanpublic double nextDouble() //随机生成doublepublic float nextFloat() //随机生成floatpublic int nextInt() //随机生成intpublic int nextInt(int)//随机生成给定最大值的intpublic long nextLong()//随机生成long值
//使用方法
Random r=new Random();

6. BigInteger类

BigInteger表示大整数类,定义在java.math包中,如果在操作时一个整型数据已经超过了整数的最大类型长度long,数据无法装入,此时可以使用BigInteger类进行操作。

常用方法如下所示:

public BigInteger(String val)//将一个字符串变为BigInteger类型的数据
public BigInteger add(BigInteger var)//加法
public BigInteger substract(BigInteger var)//减法
public BigInteger multiply(BigInteger var)//乘法
public BigInteger divide(BigInteger var)//除法
public BigInteger max(BigInteger var)//最大值
public BigInteger min(BigInteger var)//最小值
public BigInteger[] divideAndRemainder(BigInterger val)
//除法操作,数组第1个元素为除法的商,第2个位除法的余数

7. 对象克隆技术

在Java中支持对象的克隆操作,直接使用Object类中的clone方法即可,方法定义如下:

protected Object clone() throws CloneNotSupportException

以上方法是受保护的类型,所以在子类中必须覆写此方法,而且覆写之后应该扩大访问权限,这样才能被外部调用,但是具体的克隆方法的实现还是在Object中,所以在覆写的方法中只需要调用Object类中的clone方法即可完成操作,而且在对象所在的类必须实现Cloneable接口才可以完成对象的克隆操作。具体例子如下所示:

class Person implements Cloneable{
  private String name=null;
  public Person(String name){
    this.name=name;
  }
  public void setName(String name){
    this.name=name;
  }
  public String getName(){
    return this.name;
  }
  //需要子类覆写clone方法
  public Object clone() throws CloneNotSupportedException{
    return super.clone();//具体的克隆操作由父类完成
  }
  public String toString(){
    return "姓名:"+this.getName();
  }
};
public class CloneDemo{
   public static void main(String[] args)throws Exception{
     Person p1=new Person("Winson");
     Person p2=(Person)p1.clone();
     p2.setName("Al");

   }
};

8. Arrays类

Arrays类是数组的操作类,定义在java.util包中,主要功能是实现数组元素的查找、数组内容的填充、排序等如下所示:(静态类Arrays.sort())。

public static 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)//输出去数组信息

9. Comparable接口

Arrays类中的sort()方法被重载多次,也可以对任意类型的数组排序,排列时会根据数值的大小进行排序。同样此方法也可以对Object数组进行排序,但是要使用此种方法排序也是有要求的,即对象所在的类必须实现Comparable接口,此接口就是用于指定对象排序规则的。Comparable接口的定义如下:

public interface Comparable<T>{
  public int compareTo(T o);
}
//其中只有一个compareTo()方法,此方法返回一个int类型的数据
//1:表示大于
//-1:表示小于
//0:表达等于
//下面使用进行排序操作
class Student implements Comparable<Student>{
//指定泛型为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\t"+age+"\t\t"+score;
   }
   //覆写compareTo()方法,实现排序规则的应用
   public int compareTo(Student stu){
     if(this.score>stu.score){
         return -1;
     }else 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;
       }
     }

   }

};
Student stu[]={new Student(...),new Student(...)};//student数组
java.util.Arrays.sort(stu);//进行排序操作

10. 观察者设计模式

多个对象观察同一个对象。

在java.util包中提供了Observable类和Observer接口,使用它们接口完成观察者模式。需要被观察的类必须继承Observable类,Observable类常用方法如下所示:

public void addObserver(Observer o)//添加一个观察者
public void deleteObserer(Observer o)//删除一个观察者
public void setChanged()//被观察者状态发生改变
public void notifyObservers(Object arg)//通知所有观察者状态改变

例子示意如下:

public interface Observer{
  void update(Observer o,Object arg);
}
//在此接口中只定义了一个update方法,第1个参数表示被观察者实例,第2个参数表示修改的内容
//实现如下:
import java.util.Observable;
import java.util.Observer;
class House extends Observable{
  private float price;
  public House(float price){
    this.price=price;
  }
  public float getPrice(){
    return price;
  }
  public void setPrice(float price){
    super.setChanged();
    super.notifyObservers(price);
    this.price=price;
  }
  public String toString(){
    return "房子价格为:"+this.price;
  }
}
class HousePriceObserver implements Observer{
  private String name;
  public HousePriceObserver(String name){
    this.name=name;
  }
  public void update(Observable obj,Object arg){
    if(arg instanceof Float){
      System.out.println(this.name+"观察到价格更改为:");
      System.out.println(((Float)arg).floatValue());
    }
  }
}
public class ObserDemo{
  public static void main(String[] args){
    House h=new House(100);
    HousePriceObserver hpo1=new HousePriceObserver("购房者1");
    HousePriceObserver hpo2=new HousePriceObserver("购房者2");
    HousePriceObserver hpo3=new HousePriceObserver("购房者3");
    h.addObserver(hpo1);
    h.addObserver(hpo2);
    h.addObserver(hpo3);
    System.out.println(h);
    h.setPrice(66);
    System.out.println(h);
  }
}

11. 正则表达式

如果要在程序中应用正则表达式则必须依靠Patern类与Matcher类,这两个类都在java.util.regex包宏定义。Pattern类的主要作用是进行正则规范的编写,而Matcher类主要是执行规范,验证一个字符串是否符合规范。具体使用如下:

Pattern.compile("[0-9]+".matcher(str).matches())
//此字符串有数字组成
//使用正则验证
//Pattern类
public static Pattern compile(String regex) //指定正则表达式规则
public Matcher matcher(CharSequence input)//返回Matcher类实例
public String[] split(CharSequence input)//字符拆分
//Matcher类
public boolean matches()//执行验证
public String replaceAll(String replacement)//字符串替换
//String类 正则表达式支持
public boolean matches(String regex)//字符串匹配
public String replaceAll(String regex,String replacement)//字符串替换
public String[] split(String regex)//字符串拆分

12. 定时调度

  • Timer类

Timer类是一种线程设施,可以用来实现在某一个时间或某一段时间后安排某一个任务执行一次或定期重复执行。该功能与TimerTask配合使用。TimerTask类用来实现有Timer安排的一次或者重复执行的某一个任务。

每一个Timer对象对应的是一个线程,因此计时器所执行的任务应该迅速完成,否则可能会延迟后序任务的执行,而这些后序任务就有可能堆在一起,等到该任务完成后才能快速连续执行,常见方法如下:

public Timer() //用来创建一个计时器并启动该计数器
public void cancel()//终止该计时器。
public int purge()//将所有已经取消的任务移除,释放内存空间
public void schedule(TimerTask task,Date time)//安排一个任务指定时间执行
//如果超过这个时间,即立即执行
public void schedule(TimerTask task,Date firstTime,long period)
//安排一个任务在指定时间执行,然后以固定频率重复执行
public void schedule(TimerTask task,long delay,long period)
public void scheduleAtFixedRate(TimerTask task,Date firstTime,long period)
//然后以近似固定的频率重复执行

要执行具体的任务,则必须使用TimerTask类。TimerTask类是一个抽象类,如果要使用该类,需要自己建立一个类来继承此类,并实现其中的抽象方法。TimerTask常见方法如下:

public void cancel() 
//用来终止此任务,如果该任务只执行一次且还没有执行,则永远不会再执行
public void run()
//该任务索要执行的具体操作,该方法引入的接口为Runnable中的方法,子类需要覆写
public long scheduled ExceptionTime()
//返回最近一次要执行该任务的时间,一般在run方法中调用,用来判断当前是否有足够
//时间来执行完成该任务
public class MyTask extends TimerTask{
  public void run(){
    SimpleDateFormat sdf=null;
    sdf=new SimpleDateFormat("yyy-MM-dd HH:mm:ss:SSS");
    System.out.println("当前系统时间为:"+sdf.format(new Date()));
  }
}
public class TestTask{
  public static void main(String[] args){
    Timer t=new Timer();
    MyTask mytask=new MyTask();
    t.schedule(mytask,1000,2000);//设置任务的执行,1秒后开始,每2秒重复
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值