Java常用类

Java常用类

自动装箱,拆箱

public class TestDemo {
    public static void main(String[] args) {

      //Integer a = new Integer (1000);
        Integer a = 1000; //jdk5.0以后,自动装箱。编译器改进代码:Integer a = new Integer(1000);

        int c = new Integer(1500); //自动拆箱。编译器改进代码:new Integer(1500).intValue();
    }
}

 

String(不可变字符序列)

String str = new String ('abcdefg')  //声明String
//常用方法
int strlength = str.length();  //返回该字符串的长度, strlength = 7

char ch = str.charAt(4); /返回字符串中指定位置的字符, "e"

String str2 = str.substring(2,5);//str2 = "cdef" //截取一段字符串

String str = "aa".concat("bb").concat("cc");
相当于String str = "aa"+"bb"+"cc";  //字符串拼接

String str = "asd!qwe|zxc#";
String[] str1 = str.split("!|#");//str1[0] = "asd";str1[1] = "qwe";str1[2] = "zxc";

int n = Integer.parseInt("12");
float f = Float.parseFloat("12.34");
double d = Double.parseDouble("1.124"); //字符串与基本类型的转换

toString //返回字符串本身, 无参
String Str = new String("abcdefg");
 System.out.println( Str.toString() );

 

可变字符序列

StringBuilder (线程不安全,效率高) , StringBuffer  (线程安全,效率低), 其他的基本相同

 

 StringBuilder sb = new StringBuilder(); //字符串长度初始为16
        StringBuilder sb1 = new StringBuilder(32); //字符串长度初始修改为32
        StringBuilder sb2 = new StringBuilder("abcd"); //value[] = {'a', 'b', 'c', 'd', \u0000, \u0000...}
        sb2.append("efg");
        sb2.append("dsadas").append("dsadsa").append("dsada"); //可以写成方法链,可以看源码,源码有return this,所以可以一直.append

        //StringBuilder长度可变, 如果去看源码, 本质是利用Arrays.copyof这个方法, 把老数组替换成新数组, 传一个新参数进去扩容
 

 

Date类

Date d = new Date();
d.setTime(123);
d.getTime();
System.currentTimeMillis(); //当前系统时间

 

DateFormat, SimpleDateFormat

public class TestDemo {
    public static void main(String[] args) {

        DateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

        Date d = new Date(234213902);
        System.out.println(df.format(d));
        
    }

}

 

日期计算

public class TestDemo {
    public static void main(String[] args) {

        Calendar c = new GregorianCalendar();
        c.set(2001, 2, 10, 12, 30, 0);
        
        //日期计算
        c.add(Calendar.YEAR, 5);
        c.add(Calendar.MONTH, -2);
    }
}

 

 

File类

public class TestDemo {
    public static void main(String[] args) {
            File f = new File("d:/src3/TestDemoFile.java");
            File f2 = new File("d:/src3"); //file可以, folder(目录)也可以
            File f3 = new File(f2, "TestFile666");

            try {
                f3.createNewFile();
            }catch(IOException e){
                e.printStackTrace();    //创建新file
        }

        f3.delete();

        f.mkdir(); 
        f.mkdirs(); //mkdirs会自动创建不存在的副目录,对mkdir来说,没有对应副目录则创建失败
    }
}

 

posted on 2018-08-30 17:14  TheExile  阅读(105)  评论(0)    收藏  举报

导航