Java Common class libraries

Source: Internet
Author: User
Tags comparable dateformat

Java Common class libraries

System class

All the methods in this class are static.

Array copy
System.arraycopy(src,dest,srcindex,destindex, Length);
Get all the properties of the system
    System.getProperties().list(System.out);
Get a property of a system
    System.getProperty("user.dir");//当前目录,还有很多其他的属性,可以在上面的获得系统全部属性那里面查看
Exit (status) status is not 0
  System.exit(1);
Garbage collection
   这个方法就是封装了java.lang.Runtime.getRuntime().gc()二者的功能是一致的   System.gc();   在对象的生命周期救赎之后,系统会在一定时间的时候对对象进行垃圾处理,调用gc()方法就是立即回收垃圾
Time
   System.currentTimeMillis();   获得1970.1.1到现在的毫秒数

Class to do something before recycling, you can rewrite the Finalize method inside the object,

//这个方法就是重写的Object里面的方法,当实例被回收的时候调用@Overrideprotected void finalize() throws Throwable {    super.finalize();}
Date Manipulation class Date
    Date date=new Date();    System.out.println(date);//格式不能自己决定
Calendar
    //Calendar 是一个接口    Calendar cal=new GregorianCalendar();    //get方法获得当前时间的一些域,这些域都在Calendar里面定义好了    System.out.println(cal.get(Calendar.MONTH)+1);//这个是从0开始算的    System.out.println(cal.get(Calendar.MILLISECOND));    System.out.println(cal.get(Calendar.DAY_OF_MONTH));

Can be more convenient to get the content of each domain, but to get specific time is the need for string concatenation, more trouble

DateFormat

Abstract class for formatting the date data, but can get his instance directly through Getdateinstance

    DateFormat df=DateFormat.getDateInstance();//获得日期实例    DateFormat df1=DateFormat.getDateTimeInstance();//获得时间日期实例
SimpleDateFormat
    //就是DateFormat的子类,更加好用。就是有重复的前面的就是大写的,否则就是小写的。y-M-d-H-m-s-S    SimpleDateFormat sf1=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SS");    SimpleDateFormat sf2=new SimpleDateFormat("yy-M-dd-HH-mm-ss");    SimpleDateFormat sf3=new SimpleDateFormat("yyyyMMddHHmmssSS");    System.out.println(sf1.format(new Date()));    System.out.println(sf2.format(new Date()));    System.out.println(sf3.format(new Date()));//获得时间戳
Math and Random class math

Methods in the math class are static methods that are called directly using the "class. Method name ()" form.

    System.out.println("求平方根:" + Math.sqrt(9.0)) ;    System.out.println("求两数的最大值:" + Math.max(10,30)) ;    System.out.println("求两数的最小值:" + Math.min(10,30)) ;    System.out.println("2的3次方:" + Math.pow(2,3)) ;    System.out.println("四舍五入:" + Math.round(33.6)) ;   想要精确位数的四舍五入,要用BigDecimal
Random
    Random rd=new Random();    System.out.println(rd.nextInt(100));//1-100之间的int    System.out.println(rd.nextDouble()); //获得0-1之间的值    System.out.println(rd.nextBoolean());
Numberformatnumberformat

This is a format that can be determined differently depending on the region.

    NumberFormat nf=NumberFormat.getInstance();    System.out.println(nf.format(100000000));//100,000,000    System.out.println(nf.format(100000.1234));//100,000.123
DecimalFormat

DecimalFormat is a subclass of NumberFormat, using more flexible

   //模板详情    /*    0  - 数字不存在时补足0    #  - 数字不存在时忽略    。 - ,    E    可以加上必要的货币单位 ¥ $    %       - 以百分号显示    \u2030  -千分数显示    * */    DecimalFormat df=new DecimalFormat("\u2030");    System.out.println(df.format(1167));    df=new DecimalFormat("###,###.###¥");    System.out.println(df.format(111222.34567));
Large number of operations

BigInteger and BigDecimal are immutable, each step of the operation, will produce a new object, because the creation of objects will incur overhead, so they are not suitable for a large number of mathematical calculations, should try to use long, float, Double and other basic types do scientific calculations or engineering calculations.

BigInteger Operation Shaping
    BigInteger bi1 = new BigInteger("123456789") ;  // 声明BigInteger对象    BigInteger bi2 = new BigInteger("987654321") ;  // 声明BigInteger对象    System.out.println("加法操作:" + bi2.add(bi1)) ;    // 加法操作    System.out.println("减法操作:" + bi2.subtract(bi1)) ;   // 减法操作    System.out.println("乘法操作:" + bi2.multiply(bi1)) ;   // 乘法操作    System.out.println("除法操作:" + bi2.divide(bi1)) ; // 除法操作    System.out.println("最大数:" + bi2.max(bi1)) ;  // 求出最大数    System.out.println("最小数:" + bi2.min(bi1)) ;  // 求出最小数    BigInteger result[] = bi2.divideAndRemainder(bi1) ; // 求出余数的除法操作    System.out.println("商是:" + result[0] +";余数是:" + result[1]) ;
BigDecimal manipulating decimals
    BigDecimal bd1=new BigDecimal("123213.12123");    BigDecimal bd2=new BigDecimal("1233");    System.out.println("bd2"+bd1.divide(bd2));    double d=bd1.doubleValue();  //获得他的double值    double dd=bd1.divide(bd2,2,BigDecimal.ROUND_HALF_UP).doubleValue();    //保留两位小数四舍五入,这就是精确位数的四舍五入的方法    System.out.println(dd);

Pay attention to divide when the result is a loop will be error, it is best to explicitly control the decimal point

Java Cloning Technology

The cloned class must implement the Cloneable method, overriding the Clone () method of the parent class

class toClone implements  Cloneable{    public Object clone() throws CloneNotSupportedException {        return super.clone();    }}

Assuming that X is a non-empty object, there should be: X.clone ()!=x is true, meaning that they are not the same object. X.clone (). GetClass () ==x.getclass () is true, they are the same type class. X.equals (X.clone ()) is true and logically should be equivalent.

Arrays
    int temp[]={5,12,4,21,46,3,1,85,3,6,1,5,31};
Judging is not equal
    System.out.println(Arrays.equals(temp,temp1));
Sort
    Arrays.sort(temp);
Convert the contents of an array directly
    System.out.println(Arrays.toString(temp));
Find the location of the number. Note that you must first sort before finding
    System.out.println(Arrays.binarySearch(temp,21));
Populating an array
    Arrays.fill(temp,12);
Comparator

When sorting objects, first this class must be comparable!! There are two ways to specify a class comparison of 1, implement comparable interface 2, create a new comparison class that implements the Compaprator interface

Comparable

The method to be implemented by the interface is CompareTo

class shuzi implements Comparable<shuzi>{    int a;    int b;    public  shuzi(int a,int b){        this.a=a;        this.b=b;    }    //1-大于 0-等于 -1-小于    @Override    public int compareTo(shuzi o) {        if(this.a>o.a){            return 1;        }        if(this.a<o.a){            return  -1;        }        if(this.b>o.b){            return 1;        }        if(this.b<o.b)            return -1;        return 0;    }}   public static void main(String[] args) {    shuzi s[]={new shuzi(1,2),new shuzi(1,3)};     Arrays.sort(s);}

The principle of the comparator is a binary sorting algorithm, followed by the middle order traversal to give the results, the following handwritten code to implement this content.

Class treesort{class node{//Inner class, specify tree node comparable data;        Node left;        Node right;        Public Node (comparable data) {This.data=data;                    public void AddNode (node node) {if (Node.data.compareTo (data) <0) {if (left==null) {                Left=node;            } else Left.addnode (node);                } else if (right==null) {right=node;        } else Right.addnode (node);    }} Node RootNode;        public void Add (comparable data) {Node newnode=new node (data);        if (rootnode==null) {rootNode = NewNode;    } else Rootnode.addnode (NewNode);    } public void Searchtree () {search (RootNode);        private void Search (node node) {if (node==null) return;        Search (Node.left); System.out.println ((Shuzi) node.data). A + "" + ((Shuzi) node.data). b);    Search (node.right); }}
Comparator

In general the use of comparable is best, but if you are tired of the original implementation of the interface is not easy to modify, then you can choose to create a new class for comparison

class myComparator implements Comparator{    @Override    public int compare(Object o1, Object o2) {        return 0;    }}调用的时候,可以在sort指定比较器shuzi s[]={new shuzi(1,2),new shuzi(1,3)};Arrays.sort(s,new myComparator());
Observer pattern

The observed class inherits observable
The main function of the observer to implement the interface observer is to notify all observers when the observed object has changed, and the observer can respond accordingly.

class obserable_Objrct extends Observable{    int x;    int y;    public void setX(int x) {        //只有在setChange()被调用后,notifyObservers()才会去调用update()        super.setChanged();  //在这里设置观察点.当有变化的时候会通知他的观察者        notifyObservers(x);//可以增加参数,在观察者update里面根据参数来判断要做的处理是一种常见的方法         this.x = x;    }    public void setY(int y) {        super.setChanged();  //在这里设置观察点.当有变化的时候会通知他的观察者        notifyObservers();        this.y = y;    }}class Observer_Object implements Observer{    @Override    public void update(Observable o, Object arg) {        //o调用Observable的toString方法,告诉你是那个类发生的变化        //arg是notifyObservers(data)告诉你的数据,无参数的时候就是null        System.out.println(o);        System.out.println(arg);    }}public class _观察者模式 {    public static void main(String[] args) {        obserable_Objrct oO=new  obserable_Objrct();        oO.addObserver(new Observer_Object());//添加一个观察者        oO.setX(121);        oO.setY(121);    }}
Regular expressions

syntax for common regular expressions

No Specification Description
1 \ means ' \ '
2 \ t Tab
3 \ n Enter
4 [ABC] Character A or B or C
5 [^ABC] Take Non-
6 [A-za-z0-9] A character consisting of an alphanumeric number
7 \d Represents a number
8 \d Represents non-numeric
9 \w Denotes alphanumeric underline
10 \w Represents a non-alphanumeric underline
11 \s White space characters
12 \s Non-whitespace characters
13 ^ The beginning of the line
14 $ End of Line
15 . Any character other than line breaks

Representation of the quantity

No Specification Description
0 X Must appear once
1 X? Occurs 0 or 1 times
2 x* Appears 0, 1, multiple times
3 x+ Appears 1 or more times
4 X{n} Appears n times
5 X{n,} Appears n or more times
6 X{m,n} Appears m-n times

Logical operations

Specification Description
Xy x followed by Y.
X| Y X or Y
The key class is the pattern-used to specify the compile regular matcher-to match
    String str="2012-12-23";    String pat="\\d{4}-\\d{2}-\\d{2}";  //  \\表示一个    Pattern pattern=Pattern.compile(pat);  //先编译一下正则表达式    Matcher matcher=pattern.matcher(str);    while(matcher.find()){        //查找匹配        }    if(matcher.matches()){        System.out.println("匹配成功");    }    String res[]=Pattern.compile("-").split(str);    for (int i = 0; i < res.length; i++) {        System.out.println(res[i]);    }
There is a lot of support for regular expressions in string, so in many cases you don't need to use the two classes above.

Matches-replaceall-split Note that the string itself does not change after the related operation

    //一定要注意转义,比如 | -->\\| 一个是字符串的,一个是正则表达式的转义    String string="qweooqeo-1231-33213=++waqend-213";    System.out.println(string.matches("-\\d{4}"));    System.out.println(string.replaceAll("-\\d{2}","+++"));//返回替换后的字符串    String res1[]= string.split("-");    for (int i = 0; i < res1.length; i++) {        System.out.println(res1[i]);    }
Timer operation

For each timer, the equivalent of starting a new thread, doing timed processing, since it is a thread, there is inevitably a delay
The timer is a timer, and TimerTask is the task to be assigned, overriding the abstract method in this abstract class Mytimertask

class Mytimertask extends TimerTask{    @Override    public void run() {        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");        System.out.println(df.format(new Date()));    }}public class _计时器 {    public static void main(String[] args) {        //对于每一个Timer,相当于启动了一个新的线程,做定时处理,既然是线程,就不可避免的有延迟        Timer timer=new Timer();        timer.scheduleAtFixedRate(new Mytimertask(),1000,100);//如果中间发生了延迟,会调整间隔,尽量满足预期执行的时间        timer.schedule(new Mytimertask(),1000);//延迟不考虑了,还是按照规定秒数间隔等待下一个操作        timer.schedule(new Mytimertask(),1000,1000);        //取消计时器        timer.cancel();    }}

Java Common Class library

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.