zoukankan      html  css  js  c++  java
  • java 常用类

    java 常用类库
    Object 类:clone(), equals(), toString()
    Runtime 类:代表 java 程序的运行环境
    定时器: Timer 和 TimerTask 类
    System 类:
    日期操作类:
    Math 类:可以进行一些常用的数学运算
    正则式:
    Random 类:随机数的获取
    常用方法:
    
    //创建并返回与该对象相同的新对象,即克隆该对象
    protected native Object clone() throws CloneNotSupportedException
    
    //比较两个对象是否相等
    public boolean equals(Object obj)
    
    //当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法
    protected void finalize() throws Throwable
    
    //返回一个对象的运行时类
    public final Class<? extends Object> getClass()
    
    //返回该对象的哈希码值
    public int hashCode()
    
    //唤醒等待池中的线程
    public final void notify()
    
    //唤醒等待池中的所有线程
    public final void notifyAll()
    
    //返回该对象的字符串表示
    public String toString()
    
    //使当前的线程等待
    public final void wait(long timeout) throws InterruptedException
    
    // 重写 toString() 方法
    class Person
    {
    	private String name;
    	private int age;
    	public Person(){}
    	public Person(String name, int age)
    	{
    		this.name = name;
    		this.age = age;
    	}
    	public String toString()
    	{
    		return ("姓名:"+this.name+",年龄:"+this.age);
    	}
    }
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		Person p = new Person("小二", 27);
    		System.out.println(p.toString());
    		System.out.println(p);
    	}
    }
    /**
    姓名:小二,年龄:27
    姓名:小二,年龄:27
    */
    看到结果一样,所以都是调用 重写的 toString() 的方法
    // ============
    //重写 equals() 方法
    class Person
    {
    	private String name;
    	private int age;
    	public Person(){}
    	public Person(String name, int age)
    	{
    		this.name = name;
    		this.age = age;
    	}
    	// 重写equals() 方法
    	public boolean equals(Object o)
    	{
    		// 判断当前对象与指定对象是否相等
    		if(o == this)
    		{
    			return true;
    		}
    		// 判断指定的对象是否为空
    		if(o == null)
    		{
    			return false;
    		}
    		// 判断指定对象是否为 Person 的实例
    		if(!(o instanceof Person))
    		{
    			return false;
    		}
    		// 将指定对象转为 Person 实例
    		Person per = (Person)o;
    		// 比较对象的属性是否相等
    		if(this.name.equals(per.name) && this.age == per.age)
    		{
    			return true;
    		}else
    		{
    			return false;
    		}
    	}
    }
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		//创建对象实例
    		Person p1 = new Person("小二", 27);
    		Person p2 = new Person("小二", 27);
    		Person p3 = new Person("小小", 30);
    		if(p1.equals(p2))
    		{
    			System.out.println("p1与p2相等");
    		}else
    		{
    			System.out.println("p1与p2不相等");
    		}
    		if(p1.equals(p3))
    		{
    			System.out.println("p1与p3相等");
    		}else
    		{
    			System.out.println("p1与p3不相等");
    		}
    	}
    }
    /**
    p1与p2相等
    p1与p3不相等
    */
    // ------------
    class Person
    {
    	private String name;
    	private int age;
    	public Person(){}
    	public Person(String name, int age)
    	{
    		this.name = name;
    		this.age = age;
    	}
    	public boolean equals(Object o)
    	{
    		if(this == o)
    		{
    			return true;
    		}
    		if(o == null)
    		{
    			return false;
    		}
    		if(!(o instanceof Person))
    		{
    			return false;
    		}
    		Person per = (Person)o;
    		if(this.name.equals(per.name) && this.age == per.age)
    		{
    			return true;
    		}else
    		{
    			return false;
    		}
    	}
    	public int hashCode()
    	{
    		final int prime = 13;
    		int result = 13;
    		result = prime * result + ((name == null) ? 0 : name.hashCode());
    		result = prime * result + age;
    		return result;
    	}
    }
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		Person p1 = new Person("小二", 27);
    		Person p2 = new Person("小二", 27);
    		Person p3 = new Person("小小", 30);
    		System.out.println("p1的哈希值:"+p1.hashCode());
    		System.out.println("p2的哈希值:"+p2.hashCode());
    		System.out.println("p3的哈希值:"+p3.hashCode());
    		if(p1.equals(p2))
    		{
    			System.out.println("p1,p2相等");
    		}else
    		{
    			System.out.println("p1,p2不相等");
    		}
    		if(p1.equals(p3))
    		{
    			System.out.println("p1,p3相等");
    		}else
    		{
    			System.out.println("p1,p3不相等");
    		}
    		
    	}
    }
    /*
    p1的哈希值:97
    p2的哈希值:97
    p3的哈希值:980
    p1,p2相等
    p1,p3不相等
    */
     // =============
    // 克隆对象
    class Person implements Cloneable
    {
    	private String name;
    	private int age;
    	public Person(){}
    	public Person(String name, int age)
    	{
    		this.name = name;
    		this.age = age;
    	}
    	public boolean equals(Object o)
    	{
    		if(this == o)
    		{
    			return true;
    		}
    		if(o == null)
    		{
    			return false;
    		}
    		if(!(o instanceof Person))
    		{
    			return false;
    		}
    		Person per = (Person)o;
    		if(this.name.equals(per.name) && this.age == per.age)
    		{
    			return true;
    		}else
    		{
    			return false;
    		}
    	}
    	public int hashCode()
    	{
    		final int prime = 13;
    		int result = 13;
    		result = prime * result+((name == null) ? 0 : name.hashCode());
    		result = prime *result + age;
    		return result;
    	}
    	// 重写 clone() 方法
    	public Object clone() throws CloneNotSupportedException
    	{
    		return super.clone();
    	}
    	public String toString()
    	{
    		return ("姓名:"+this.name+",年龄:"+this.age);
    	}
    }
    public class Hi
    {
    	public static void main(String[] args) throws CloneNotSupportedException
    	{
    		Person p1 = new Person("小二", 27);
    		Person p2 = (Person)p1.clone();
    		System.out.println(p1+",p1的哈希码:"+p1.hashCode());
    		System.out.println(p2+",p2的哈希值:"+p2.hashCode());
    		if(p1.equals(p2))
    		{
    			System.out.println("p1和p2相等");
    		}else
    		{
    			System.out.println("p1和p2不相等");
    		}
    	}
    }
    /*
    姓名:小二,年龄:27,p1的哈希码:9761129
    姓名:小二,年龄:27,p2的哈希值:9761129
    p1和p2相等
    */
    // ==========
    java.lang.Runtime 类封装了运行时的环境
    常用方法:
    
    //向java虚拟机返回可用处理器的数目
    public int availableProcessors()
    
    //在单独的进程中执行指定的字符串命令
    public Process exec(String command) throws IOException
    
    //
    public void exit(int status)
    
    //返回 java 虚拟机中的空闲内存量
    public long freeMemory()
    
    //运行垃圾回收
    public void gc()
    
    //返回与当前 java 应用程序相关的运行时对象
    public static Runtime getRuntime()
    
    //强行终止目前正在运行的 java虚拟机
    public void halt(int status)
    
    //加载具有指定库名的动态库
    public void load(String libname)
    
    //返回 java虚拟机试图使用的最大内存量
    public long maxMemory()
    
    //返回 java虚拟机中的内存总量
    public long totalMemory()
    
    // ===========
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		// 获取当前运行的对象
    		Runtime rt = Runtime.getRuntime();
    		System.out.println("JVM处理器的数目:"+rt.availableProcessors());
    		System.out.println("JVM空闲内存量:"+rt.freeMemory());
    		System.out.println("JVM内存总量:"+rt.totalMemory());
    		System.out.println("JVM最大内存量:"+rt.maxMemory());
    		String str = null;
    		for(int i=0; i<10000; i++)
    		{
    			str =""+i;
    		}
    		System.out.println("操作 str后,jvm空闲内存量:"+rt.freeMemory());
    		// 回收
    		rt.gc();
    		System.out.println("回收垃圾后,JVM空闲内存量:"+rt.freeMemory());
    	}
    }
    /*
    JVM处理器的数目:2
    JVM空闲内存量:62455464
    JVM内存总量:64487424
    JVM最大内存量:947388416
    操作 str后,jvm空闲内存量:61448808
    回收垃圾后,JVM空闲内存量:63341168
    */
    // ==========
    
    Process 类
    可用来控制进程并获取相关信息
    常用方法:
    //关闭子进程
    public abstract void destory()
    
    //返回子进程的出口值
    public abstract int exitValue()
    
    //获得子进程的错误流
    public abstract InputStream getErrorStream()
    
    //获得子进程的输入流
    public abstract InputStream getInputStream()
    
    //获得子进程的输出流
    public abstract OutputStream getOutputStream()
    
    //导致当前进程等待
    public abstract int waitFor() throws InterruptedExeption
    
    // ========
    // 以下是调用了 process
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		// 获取 Runtime 运行时的对象
    		Runtime rt = Runtime.getRuntime();
    		Process process = null;
    		try
    		{
    			// 调用本机的计算器
    			process = rt.exec("calc.exe");
    		}catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    // --------------
    //以下 5秒后不会关闭计算器
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		Runtime rt = Runtime.getRuntime();
    		try
    		{
    			rt.exec("calc.exe");
    		}catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    		try
    		{
    			Thread.sleep(5000);
    		}catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    
    //以下5秒后会关闭计算器
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		Runtime rt = Runtime.getRuntime();
    		Process process = null;
    		try
    		{
    			process = rt.exec("calc.exe");
    		}catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    		try
    		{
    			Thread.sleep(5000);
    		}catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    		process.destroy();
    	}
    }
    // ==========
    定时器, Timer 与 TimerTask 类
    java.util.Timeer
    java.util.TimerTask
    Timer 类的常用方法
    
    //创建一个新计时器
    public Timer()
    
    //创建一个新计时器,并指定相关线程作为守护线程
    public Timer(boolean isDaemon)
    
    //创建一个新计时器,并为指定的相关线程设置名称
    public Timer(String name)
    
    //创建一个新计时器,指定相关线程作为守护线程,并为指定的相关线程设置名称
    public Timer(String name, boolean isDaemon)
    
    //终止此计时器
    public void cancel()
    
    //移除所有已取消的任务,用于释放内存空间
    public int purge()
    
    //安排在指定的时间执行指定的任务,若已超过该时间,则立即执行
    public void schedule(TimerTask task, Date time)
    
    //安排在指定的时间执行指定的任务,然后以固定的频率(单位 ms)重复执行
    public void schedule(TimerTask task, Date firstTIME, long period)
    
    //安排指定的任务在一段时间后(ms)执行
    public void schedule(TimerTask task, long delay)
    
    //安排指定的任务在一段时间后执行,然后以固定的频率重复执行
    public void schedule(TimerTask task,long delay, long period)
    
    // 安排在指定的时间执行指定的任务,以后以近似的频率重复执行
    public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
    
    //安排指定的任务在指定的时间后执行,并重复执行
    public void scheduleAtFirstRate(TimerTask task, long delay, long period)
    
    // TimerTask 类
    常用方法
    // 取消此计时器任务
    public boolean cancel()
    
    //此计时器任务要执行的操作编写在该方法中,子类必须重写该方法
    public abstract void run()
    
    //返回此任务最近要执行的任务时间
    public long scheduledExceptionTime()
    
    // ==========
    // 定时操作
    import java.util.Date;
    import java.util.Random;
    import java.util.Timer;
    import java.util.TimerTask;
    // 任务调度类继承 TimerTask
    class RemindTask extends TimerTask
    {
    	public void run()
    	{
    		System.out.println("执行时间:"+(new Date()));
    	}
    }
    public class Hi
    {
    	Timer timer;
    	public Hi(int seconds, int lenTimer)
    	{
    		// 建立 Timer类对象
    		timer = new Timer();
    		// 执行任务
    		timer.schedule(new RemindTask(),seconds, lenTimer);
    	}
    	public static void main(String[] args)
    	{
    		System.out.println("任务调度开始....");
    		// 设置任务, 500 ms 后开始,每 1s 重复一次
    		new Hi(500,1000);
    	}
    }
    // ------------
    System 类常用属性和方法
    // 常量,“标准”错误输出流
    public static PrintStream err
    
    //常量,“标准”输入流
    public static PrintStream in
    
    //常量,“标准”输出流
    public static PrintStream out
    
    //从指定的源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束,
    //其中,src为源数组,srcPos表示源数组的起始索引
    // dest 表示目的数组, destPos表示目的数组的起始索引,
    // length 表示提制数组 的长度
    public static void arraycopy(Object src, int srcPos, Object dest,
    		int destPos, int length)
    		
    //返回以 ms 为单位的当前时间
    public static long currentTimeMillis()
    
    //
    public static void exit(int status)
    
    //运行垃圾回收器
    public static void gc()
    
    //获得指定的环境变量值
    public static String getenv(String name)
    
    //确定当前的系统属性
    public static Properties getProperties()
    
    //
    public static void load(String filename)
    // =========
    // 获取系统属性
    import java.util.Properties;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		// 取得系统属性
    		Properties pr = System.getProperties();
    		//列出属性
    		pr.list(System.out);
    	}
    }
    // ----------
    //复制数组
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		char src[] = {'A', 'B', 'C', 'D', 'E', 'F'};
    		char dest[] = {'1','2','3', '4', '5'};
    		System.arraycopy(src, 1, dest, 1, 2);
    		for (char c:dest)
    		{
    			System.out.print(c+" ");
    		}
    	}
    }
    
    //1 B C 4 5
    // ==============
    //程序运行计时
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		long startTime = System.currentTimeMillis();
    		long result = 0;
    		for (long i=0; i<888888888L; i++)
    		{
    			result += i;
    		}
    		System.out.println("程序运行时间:"+(System.currentTimeMillis()-startTime));
    	}
    }
    //程序运行时间:732
    // --------------
    /*
     * 垃圾对象的回收
     * System.gc() 可用于垃圾回收器,实际是调用了 Runtime 类的 gc() 方法
     * 可用 Object类的 finalize() 方法来释放一个对象占用的内存空间
     */
    class Person
    {
    	private String name;
    	private int age;
    	public Person(){}
    	public Person(String name, int age)
    	{
    		this.name = name;
    		this.age = age;
    	}
    	public String toString()
    	{
    		return ("姓名:"+this.name+",年龄:"+this.age);
    	}
    	public void finalize() throws Throwable
    	{
    		System.out.println("释放对象:"+this);
    		super.finalize();
    	}
    }
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		Person p = new Person("小二", 27);
    		System.out.println(p);
    		p = null;
    		System.gc();
    	}
    }
    /*
    姓名:小二,年龄:27
    释放对象:姓名:小二,年龄:27
    */
    // ===========
    Date类常用方法:
    
    //生成一个 Date对象,以表示分配它的时间,精确到毫秒
    //该构造方法调用 System.currentTimeMillis()方法获取当前时间
    //即 new Date() 等价于 new Date(System.currentTimeMillis())
    public Date()
    
    //根据指定的 long 类型值来生成一个 Date对象,表示时间戳,以 ms 为单位
    public Date(long date)
    
    //测试此日期是否指定日期之后
    public boolean after(Date when)
    
    //测试此日期是否在指定日期之前
    public boolean before(Date when)
    
    //比较两个日期的顺序,早为 -1,相等为0.晚为 1
    public int compareTo(Date anotherDate)
    
    //比较两日期相等性
    public boolean equals(Object obj)
    
    //返回自 1970-01-01到 Date 对象的时间差,单位为 ms
    public long getTime()
    
    //设置此 Date对象,惟 1970-01-01以后 time毫秒的时间点
    public setTime(long time)
    
    //把 Date对象转换为以下形式 down mon dd hh:mm:ss zzz yyy
    public String toString()
    // ---------
    // 验证 Date类
    import java.util.Date;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		//攻取当前时间
    		Date date1 = new Date();
    		//当前时间+123ms
    		Date date2 = new Date(System.currentTimeMillis()+123);
    		System.out.println("时间:"+date1);
    		//输出date2,以时间差表示
    		System.out.println("时间差:"+date2.getTime()+"ms");
    	
    		System.out.println("date1是date2是否相同:"+date1.compareTo(date2));
    		System.out.println("date1是否比 date2早:"+date1.before(date2));
    	}
    }
    /*
    时间:Sun Mar 01 13:43:52 CST
    时间差:1425188632171ms
    date1是date2是否相同:-1
    date1是否比 date2早:true
    */
    // ===========
    // 不推荐使用 Date表示日期和时间,应用用 Calendar 类,这个是抽象类,所以不能直接实例化,
    //可用两种:子类 GregorianCalendar 为其实例化,通过 Calendar 类中的 getInstance() 方法
    // =======
    //验证 Calendar 类
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		Calendar call = Calendar.getInstance();
    		Calendar cal2 = new GregorianCalendar();
    		System.out.println("年份:"+call.get(Calendar.YEAR));
    		System.out.println("月分:"+(call.get(Calendar.MONTH)+1));
    		System.out.println("号数:"+(call.get(Calendar.DATE)));
    		System.out.println("今年的第"+(call.get(Calendar.DAY_OF_YEAR))+"天");
    		System.out.println("本月的第"+(call.get(Calendar.DAY_OF_MONTH))+"天");
    		System.out.println("本月的第"+(call.get(Calendar.DAY_OF_WEEK_IN_MONTH))+"周");
    		System.out.println("星期:"+(call.get(Calendar.DAY_OF_WEEK)-1));
    		System.out.println("24小时制:"+call.get(Calendar.HOUR_OF_DAY));
    		System.out.println("12小时制:"+call.get(Calendar.HOUR));
    		System.out.println("分钟:"+call.get(Calendar.MINUTE));
    		System.out.println("秒:"+call.get(Calendar.SECOND));
    		System.out.println("毫秒:"+call.get(Calendar.MILLISECOND));
    		System.out.println("日期:"+call.getTime());
    		cal2.set(2015,10,3);
    		long time = cal2.getTimeInMillis() - call.getTimeInMillis();
    		long day = time/(24*60*60*1000);
    		System.out.println("天数:"+day);
    		
    	}
    }
    /*
    年份:2015
    月分:3
    号数:1
    今年的第60天
    本月的第1天
    本月的第1周
    星期:0
    24小时制:15
    12小时制:3
    分钟:24
    秒:13
    毫秒:672
    日期:Sun Ma
    天数:247
    */
    // ----------
    
    日期格式类: DateFormat 类,为抽象类
    可使用 DateFormat类中的静态方法 getDateFormat()实例化
    
    import java.util.Date;
    import java.text.DateFormat;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		DateFormat df1 = DateFormat.getInstance();
    		DateFormat df2 = DateFormat.getDateInstance();
    		DateFormat df3 = DateFormat.getTimeInstance();
    		DateFormat df4 = DateFormat.getDateTimeInstance();
    		
    		System.out.println("默认:"+df1.format(new Date()));
    		System.out.println("Date 默认:"+df2.format(new Date()));
    		System.out.println("Time默认:"+df3.format(new Date()));
    		System.out.println("DateTime默认:"+df4.format(new Date()));
    	}
    }
    /*
    默认:15-3-1 下午3:41
    Date 默认:2015-3-1
    Time默认:15:41:13
    DateTime默认:2015-3-1 15:41:13
    */
    // --------------
    //中文时间格式
    import java.util.Date;
    import java.util.Locale;
    import java.text.DateFormat;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		DateFormat dfShort = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,Locale.CHINA);
    		DateFormat dfMedium = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.CHINA);
    		DateFormat dfFull = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.CHINA);
    		DateFormat dfLong = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG,Locale.CHINA);
    
    		DateFormat dfDefault = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
    		System.out.println("short型:"+dfShort.format(new Date()));
    		System.out.println("medium型:"+dfMedium.format(new Date()));
    		System.out.println("Full 型:"+dfFull.format(new Date()));
    		System.out.println("Long型:"+dfLong.format(new Date()));
    		System.out.println("DEFAULT型"+dfDefault.format(new Date()));	
    	}
    }
    /*
    short型:15-3-1 下午4:23
    medium型:2015-3-1 16:23:42
    Full 型:2015年3月1日 星期日 下
    Long型:2015年3月1日 下午04时2
    DEFAULT型2015-3-1 16:23:42
    */
    // ============
    //自定义日期格式类
    //SimpleDateFormat 类
    import java.util.Date;
    import java.text.SimpleDateFormat;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		String format1 = "yyyy年MM月dd日 HH:mm:ss E";
    		String format2 = "yyyy-MM-dd HH:mm:ss";
    		SimpleDateFormat sdf1 = new SimpleDateFormat(format1);
    		SimpleDateFormat sdf2 = new SimpleDateFormat(format2);
    		String date1 = sdf1.format(new Date());
    		String date2 = sdf2.format(new Date());
    		System.out.println(date1);
    		System.out.println(date2);
    	}
    }
    /*
    2015年03月01日 16:48:04 星期日
    2015-03-01 16:48:04
    */
    // ------------
    //追念日期的字符串转换为日期 Date类型
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.text.ParseException;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		String strDate = "2015-03-01 16:06:06";
    		String format = "yyyy-MM-dd HH:mm:ss";
    		SimpleDateFormat sdf = new SimpleDateFormat(format);
    		Date date = null;
    		try
    		{
    			date = sdf.parse(strDate);
    		}catch(ParseException e)
    		{
    			e.printStackTrace();
    		}
    		System.out.println(date);
    	}
    }
    //Sun Mar 01 16:06:06 CST 2015
    // ============
    Math 数学运算
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		System.out.println("绝对值函数:10.02 = "+Math.abs(10.02D)+", -10.02="+Math.abs(-10.02D));
    		System.out.println("最大值最小值(23,12):最大值:"+Math.max(23, 12)+",最小值:"+Math.min(23, 12));
    		System.out.println("四舍五入:13.6 ="+Math.round(13.6)+",13.4="+Math.round(13.4));
    		System.out.println("三角函数: sin(30)="+Math.sin(30)+",cos(30)="+Math.cos(30));
    		System.out.println("开方函数:16的开方="+Math.sqrt(16)+",8的立方根="+Math.cbrt(8));
    		System.out.println("对数函数:ln(10)="+Math.log(10));
    		System.out.println("随机数:0-10 = "+Math.random()*10);
    	}
    }
    // ========
    //随机数类,Random 类,其实可以通过 Math.random()生成
    常用方法:
    public Random(),
    public Random(long seed),
    protected int next(int bits),
    public boolean nextBoolean(),
    public void nextBytes(byte[] bytes)
    public double nextDouble()
    public float nextFloat()
    public double nextGaussian()
    public int nextInt()
    public int nextInt(int n)
    public long nextLong()
    public void setSeed(long seed)
    // ---------
    // 生成指定区域的随机数
    import java.util.Random;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		Random random = new Random();
    		System.out.println("生成0-1的随机小数:"+random.nextDouble());
    		System.out.println("生成0-10.0的随机小数:"+random.nextDouble()*10);
    		System.out.println("生成5-15的随机整数:"+random.nextInt(10)+5);
    		System.out.println("生成0-100的随机数:");
    		for(int i=0;i<10; i++)
    		{
    			System.out.print(random.nextInt(100)+" ");
    		}
    	}
    }
    
    // =========
    // 具有相同种子数
    import java.util.Random;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		Random random1 = new Random(100);
    		Random random2 = new Random(100);
    		System.out.println("种子数为100的random对象:");
    		for(int i=0; i<10; i++)
    		{
    			System.out.print(random1.nextInt(100)+" ");
    		}
    		System.out.println("
    种子为100的random对象:");
    		for(int i=0; i<10; i++)
    		{
    			System.out.print(random2.nextInt(100)+" ");
    		}
    	}
    }
    /*
    种子数为100的random对象:
    15 50 74 88 91 66 36 88 23 13
    种子为100的random对象:
    15 50 74 88 91 66 36 88 23 13
    */
    //以上初始化种子数一样,所以结果一样,为了不一样,只能实例化一次 Random
    // ----------
    NumberFormat
    java.text.NumberFormat类用于数字格式化,用于各种格式化
    
    //返回所有语言环境的数组
    public static Locale[] getAvailableLocales()
    
    //获取格式化货币值时此数字格式使用的货币符号
    public Currency getCurrency()
    
    //规范格式
    public String format(double number)
    
    //返回当前默认语言环境的货币格式符号
    public static NumberFormat getCurrencyInstance()
    
    //返回指定语言环境的货币格式符号
    public static NumberFormat getCurrencyInstance(Locale inLocale)
    
    //返回当前默认语言环境的数字格式
    public static NumberFormat getInstance()
    
    //返回指定语言环境的数字格式
    public static NumberFormat getInstance(Locale inLocale)
    
    //返回当前默认语言环境的整数格式
    public static NumberFormat getIntegerInstance()
    
    //返回指定语言环境的整数格式
    public static NumberFormat getIntegerInstance(Locale inLocale)
    
    //返回当前默认语言环境的通用数字格式
    public static NumberFormat getNumberInstance()
    
    //返回指定语言环境的通用数字格式
    public static NumberFormat getNumberInstance(Locale inLocale)
    
    //返回当前默认语言环境的百分比格式
    public static NumberFormat getPercentInstance()
    
    //返回指定语言环境的百分比格式
    public static NumberFormat getPercentInstance(Locale inLocale)
    
    //将给定追念数字的字符串,解析为一个数字
    public Number parse(String source)
    
    //获取格式化货币值时此数字格式使用的货币
    public void setCurrency(Currency currency)
    
    // ============
    import java.text.NumberFormat;
    import java.util.Locale;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		System.out.println("----------默认格式(中文)------");
    		NumberFormat nfm1 = NumberFormat.getInstance();
    		System.out.println(nfm1.format(99999));
    		System.out.println(nfm1.format(9999.3601));
    		System.out.println("----------指定格式(美国)-------");
    		NumberFormat nfm2 = NumberFormat.getCurrencyInstance(Locale.US);
    		System.out.println(nfm2.format(9998774));
    		System.out.println(nfm2.format(9999.3366));
    		System.out.println("-----------默认格式(中文)--------");
    		NumberFormat nfm3 = NumberFormat.getPercentInstance();
    		System.out.println(nfm3.format(0.123));
    	}
    }
    /*
    ----------默认格式(中文)------
    99,999
    9,999.36
    ----------指定格式(美国)-------
    $9,998,774.00
    $9,999.34
    -----------默认格式(中文)--------
    */
    // --------------
    
    decimalFormat 是 NumberFormat的一个子类,用于格式化,但得有格式化模板标记
    import java.text.DecimalFormat;
    import java.util.Locale;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		// 实例化
    		DecimalFormat dfm1 = new DecimalFormat("000,000.000");
    		System.out.println("000,000.000格式:"+dfm1.format(123456.789));
    		DecimalFormat dfm2 = new DecimalFormat("###,###.###");
    		System.out.println("###,###.###格式:"+dfm2.format(123456.789));
    		DecimalFormat dfm3 = new DecimalFormat("¥000,000.000");
    		System.out.println("¥000,000.000格式:"+dfm3.format(123456.789));
    		DecimalFormat dfm4 = new DecimalFormat("$000,000.000");
    		System.out.println("$000,000.000格式:"+dfm4.format(123456.789));
    		DecimalFormat dfm5 = new DecimalFormat("###,###.###%");
    		System.out.println("###,###.###%格式:"+dfm5.format(123456.789));
    		DecimalFormat dfm6 = new DecimalFormat("000.###u2030");
    		System.out.println("000.###u2030格式:"+dfm6.format(123456.789));
    		DecimalFormat dfm7 = new DecimalFormat("###.###");
    		System.out.println("###.###格式:"+dfm7.format(123456.789));
    	}
    }
    /*
      值为 123456.789
    结果如下:
    000,000.000格式:123,456.789
    ###,###.###格式:123,456.789
    ¥000,000.000格式:¥123,456.789
    $000,000.000格式:$123,456.789
    ###,###.###%格式:12,345,678.9%
    000.###‰格式:123456789‰
    ###.###格式:123456.789
    */
    
    //-------------
    大数类
    BigInteger:无限大的整数
    BigDecimal:无限大的浮点数
    //BigInteger 类
    import java.math.BigInteger;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		String strNumber1 = "123456789987654321";
    		String strNumber2 = "987654321123456789";
    		BigInteger big1 = new BigInteger(strNumber1);
    		BigInteger big2 = new BigInteger(strNumber2);
    		System.out.println("加法操作:"+big1.add(big2));
    		System.out.println("减法操作:"+big2.subtract(big1));
    		System.out.println("乘法操作:"+big1.multiply(big2));
    		System.out.println("除法操作:"+big2.divide(big1));
    		System.out.println("取模操作:"+big2.mod(big1));
    		System.out.println("最大公约数:"+big1.gcd(big2));
    		System.out.println("最大值:"+big1.max(big2)+",最小值:"+big1.min(big2));
    		byte b[] = big1.toByteArray();
    		System.out.println("二进制补码:");
    		for(int i=0; i<b.length;i++)
    		{
    			System.out.print(b[i]+" ");
    		}
    	}
    }
    /*
    加法操作:1111111111111111110
    减法操作:864197531135802468
    乘法操作:121932632103337905662094193112635269
    除法操作:8
    取模操作:1222222221
    最大公约数:1222222221
    最大值:987654321123456789,最小值:123456789987654321
    二进制补码:
    1 -74 -101 75 -32 82 -6 -79
    */
    // ==============
    //精确的大数类: BigDecimal类
    因为 float double 不适合精确运算
    import java.math.BigDecimal;
    public class Hi
    {
    	public static double add(double d1, double d2)
    	{
    		BigDecimal dbl1 = new BigDecimal(d1);
    		BigDecimal dbl2 = new BigDecimal(d2);
    		return dbl1.add(dbl2).doubleValue();
    	}
    	public static double sub(double d1, double d2)
    	{
    		BigDecimal dbl1 = new BigDecimal(d1);
    		BigDecimal dbl2 = new BigDecimal(d2);
    		return dbl1.subtract(dbl2).doubleValue();
    	}
    	public static double mul(double d1, double d2)
    	{
    		BigDecimal dbl1 = new BigDecimal(d1);
    		BigDecimal dbl2 = new BigDecimal(d2);
    		return dbl1.multiply(dbl2).doubleValue();
    	}
    	public static double div(double d1, double d2, int len)
    	{
    		BigDecimal dbl1 = new BigDecimal(d1);
    		BigDecimal dbl2 = new BigDecimal(d2);
    		return dbl1.divide(dbl2,len, BigDecimal.ROUND_HALF_UP).doubleValue();
    	}
    	public static double round(double d1, int len)
    	{
    		BigDecimal dbl1 = new BigDecimal(d1);
    		BigDecimal dbl2 = new BigDecimal(1);
    		return dbl1.divide(dbl2,len,BigDecimal.ROUND_HALF_UP).doubleValue();
    	}
    	public static void main(String[] args)
    	{
    		System.out.println("加法操作:"+round(add(9.87645321, 1.2369875), 1));
    		System.out.println("减法操作:"+round(sub(9.87654321,1.23456789), 1));
    		System.out.println("乘法操作(保留5位小数:"+round(mul(9.87654321,1.23456789), 5));
    		System.out.println("除法操作(保留10位小数):"+div(9.87654321,1.23456789,10));
    	}
    }
    /*
    加法操作:11.1
    减法操作:8.6
    乘法操作(保留5位小数:12.19326
    除法操作(保留10位小数):8.0000000729
    */
    // ===========
    正则表达式,由 java.util.regex 包
    该包中只有两个类 Pattern类和Match类
    Pattern类的对象是正则表达式编译在内存的表示形式,而 Matcher对象是状态机,它依据 Pattern对象作为匹配模式,
    对字符串展开匹配操作
    执行流程如下:
    首先创建 Pattern对象,再由已定义的正则表达式对它进行编译。最后再利用
    Pattern对象创建对应的 Matcher对象,执行匹配所涉及的状态保存在 Matcher对象中
    // =============
    Pattern类常用方法
    //编译并创建一个Pattern类的对象
    public static Pattern compile(String regex)
    
    //同上,但增加一个 flags参数标志模式
    public static Pattern compile(String regex, int flags)
    
    //返回当前Pattern对象的 flags参数
    public int flags()
    
    //创建一个给定名称的 Matcher对象
    public Matcher matcher(CharSequence input)
    
    //编译给定正则表达式,并输入的字符串以正则表达式为模展开匹配
    public static boolean matcher(String regex, CharSequence input)
    
    //返回 该 Pattern对象所编译的正则表达式
    public String pattern()
    
    //将字符串按指定的正则分割
    public String[] split(CharSequence input)
    
    //将字符串进行分割,并增加分割段数
    public String[] split(CharSequence input, int limit)
    
    // =================
    //拆分字符串
    import java.util.regex.Pattern;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		String str = "好的/雷劈/去你的/恩";
    		//创建 Pattern实例
    		Pattern pat = Pattern.compile("[/]");
    		//分割字符串
    		String rse[] = pat.split(str);
    		System.out.println("分割前:
    "+str);
    		System.out.println("分割后:");
    		for(int i=0; i<rse.length; i++)
    		{
    			System.out.println(rse[i]);
    		}
    	}
    }
    /*
    分割前:
    好的/雷劈/去你的/恩
    分割后:
    好的
    雷劈
    去你的
    恩
    */
    // ==============
    
    Mathcher类需要配合 pattern类使用
    以下是部分方法:
    //将当前的子字符串替换为指定的字符串
    public Matcher appendReplacement(StringBuffer sb, String replacement)
    
    //在最后一镒匹配后,将剩余的字符串添加到指定的 StringBuffer对象中
    public StringBuffer appendTail(StringBuffer sb)
    
    //返回最后匹配的索引位置
    public int end()
    
    //返回最后与指定组匹配的位置
    public int end(int group)
    
    //在目标字符串查找下一个匹配的字符串,找到则 true
    public boolean find()
    
    //重新查找下一个匹配的字符串
    public boolean find(int start)
    // =============
    import java.util.Scanner;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Hi
    {
    	public static void main(String[] args)
    	{
    		//定义规则
    		String regex = "^(\d{2})$";
    		Scanner scan = new Scanner(System.in);
    		String str = scan.next();
    		// 实例化 Pattern
    		Pattern pat = Pattern.compile(regex);
    		// 实例化 Matcher
    		Matcher mat = pat.matcher(str);
    		if(mat.matches())
    		{
    			System.out.println("Yes");
    		}else
    		{
    			System.out.println("No");
    		}
    	}
    }
    // ============
    

      

  • 相关阅读:
    WinCE 测试网速
    YII 关联表查询
    YII CMenu配置
    php扩展开发笔记1
    使用Mysql EXPLAIN分析、优化SQL语句
    使用Mysql EXPLAIN分析、优化SQL语句 (续)
    jquery提交中文导致乱码
    *nix 命令记(持续更新)
    php 函数中使用static
    xmlhttprequest获取TransferEncoding:chunked分时编码输出
  • 原文地址:https://www.cnblogs.com/lin3615/p/4306060.html
Copyright © 2011-2022 走看看