java基础学习笔记(三)
1、裝箱和拆箱
所有基本類型都有對應的類類型,比如int對應的類是Integer,這種類就叫做封裝類。數字封裝類有Byte、Short、Integer、Long、Float、Double這些類都是抽象類Number的子類。封裝類和基本類型之間可以相互轉換,而基本類型自動轉封裝類型就叫裝箱,反之則是拆箱,代碼如下
int i = 5;//基本類型轉換成封裝類型Integer it = new Integer(i);//自動轉換就叫裝箱,通過=符號Integer it2 = i;//Integer是Number的子類,所以打印trueSystem.out.println(it instanceof Number);//封裝類型轉換成基本類型int i2 = it.intValue();?
2、字符串轉換:數字轉字符串:方法一使用String 類的靜態方法valueOf(); 方法二是把基本類型裝箱為封裝類型,然后調用封裝類類型的toString();
int i = 5;String str = String.valueOf(i);//方法一使用封裝類的valueOf方法Integer it = i; //自動轉換裝箱String str2 = it.toString(); //調用字符串封裝類的toString方法?
?
3、數學方法:java.lang.Math提供了一些常用的數學運算方法,并且都是以靜態方法的形式存在。如Math.round()是四省五入,Math.sqrt(9)是開平方,Math.pow(2,4)是2的4次方,Math.E是自然常數。
?
4、格式化輸出:輸出時如果變量過多時會用字符串拼接,拼接會顯得繁瑣,另一種解決方式是格式化輸出,printf和format能夠達到一模一樣的效果,其中%s表示字符串,%d表示數字,%n表示換行。如下:
String sentenceFormat="%s 在進行了連續 %d 次擊殺后,獲得了 %s 的稱號%n"; System.out.printf(sentenceFormat, "teemo", 5,"超神"); System.out.format(sentenceFormat, "teemo", 5,"超神");?
5、Char基本類型對應的封裝類型是Character,Character常用靜態方法如下:
System.out.println(Character.isLetter('a'));//判斷是否為字母System.out.println(Character.isDigit('a')); //判斷是否為數字System.out.println(Character.isWhitespace(' ')); //是否是空白System.out.println(Character.isUpperCase('a')); //是否是大寫System.out.println(Character.isLowerCase('a')); //是否是小寫System.out.println(Character.toUpperCase('a')); //轉換為大寫System.out.println(Character.toLowerCase('A')); //轉換為小寫String a = 'a'; //不能夠直接把一個字符轉換成字符串String a2 = Character.toString('a'); //轉換為字符串?
6、字符串使用:String 被修飾為final,所以不能被繼承。String的成員變量是private final 的,所以String 是immutable的,表現像個常量。如String s=”abc”;s=”123”;字符串創建的內容并沒有改變,s引用指向發生改變了,“abc”和“123”是兩個字符串對象,在內存空間上占兩個位置。
?
7、獲取隨機字符串的多種方法:
ASCII碼對照表
方法1,思路是隨機獲取字母數字ASCII碼數對應范圍內的數,判斷是否是字母或數字,循環獲取5個滿足要求的字符拼接成字符串
char cs[] = new char[5];short start = '0';short end = 'z'+1;for (int i = 0; i < cs.length; i++) {while (true) {char c = (char) ((Math.random() * (end - start)) + start);if (Character.isLetter(c) || Character.isDigit(c)) {cs[i] = c;break;}}}String result = new String(cs);System.out.println(result);方法2,思路是將所有數字、字母字符拼接成一個字符串,再隨機獲取字符
String pool = "";for (short i = '0'; i <= '9'; i++) {pool+=(char)i;}for (short i = 'a'; i <= 'z'; i++) {pool+=(char)i;}for (short i = 'A'; i <= 'Z'; i++) {pool+=(char)i;}char cs2[] = new char[5];for (int i = 0; i < cs2.length; i++) {int index = (int) (Math.random()*pool.length());cs2[i] = pool.charAt( index );}String result2 = new String(cs2);System.out.println(result2);方法3:思路是在數字字母分塊對應的ASCII碼數值間獲取隨機數,循環多次獲取隨機數轉換成字符拼接成字符串
public class TestNumber {public static void main(String[] args) {// TODO Auto-generated method stubchar[] chars = new char[5]; // 創建字符數組,每一個字符都將隨機獲取String str = ""; // 空字符串用來最后組合隨機字符的for (int i = 0; i < chars.length; i++) {chars[i] = getRadomChar();str += chars[i];}System.out.println(str);}public static char getRadomChar() {int m1 = (int) (Math.random() * (90 - 65)) + 65;int m2 = (int) (Math.random() * (57 - 48)) + 48;int m3 = (int) (Math.random() * (122 - 97)) + 97;int[] m = { m1, m2, m3 };int index = (int) Math.floor((Math.random() * 3));char c = (char) m[index];System.out.println(c);return c;}}其中
public static void main(String[] args) {//獲取拼接好的所有字符//在for循環中采用StringBuilder比用String的 `+=`高效;StringBuilder strPool_tmp = new StringBuilder(); for(short i='0';i<'z';i++) {if(Character.isLetter((char)i)||Character.isDigit((char)i)) {strPool_tmp.append((char)i);}}System.out.println(strPool_tmp.toString());}?
8、窮舉法(枚舉法):
枚舉法是在分析問題時,逐個列舉出所有可能情況,然后根據條件判斷此答案是否合適,合適就保留,不合適就丟棄,最后得出一般結論。主要利用計算機運算速度快、精確度高的特點,對要解決問題的所有可能情況,一個不漏地進行檢驗,從中找出符合要求的答案,因此枚舉法是通過犧牲時間來換取答案的全面性。
????說白了,就是通過循環或者遞歸,把所有可能的情況過一遍,符合條件就留下,不符合繼續找。
?
9、遞歸算法。遞歸的基本思想是把規模大的問題轉化為規模小的相似的子問題來解決。在函數實現時,因為解決大問題的方法和解決小問題的方法往往是同一個方法,所以就產生了調用它自身的情況。遞歸是利用系統的堆棧保存函數當中的局部變量來解決問題的,因為函數調用的開銷,遞歸常常會帶來效率問題。
//斐波拉契數列問題。找出數列中指定index位置的數值 1,1,2,3,5,8,13,21,34,55public static int getNum(int testNum) { if(testNum<3) {return 1;}else {return getNum(testNum-1)+getNum(testNum-2);}}?
10、字符串方法:
charAt(int index)獲取指定位置的字符;toCharArray()是將字符串轉換為對應的字符數組;subString?截取子字符串;split?根據分隔符進行分隔生成字符串數組;trim?去掉首尾空格后返回新的字符串;toLowerCase 返回全部變成小寫 ,toUpperCase 返回全部變成大寫的字符串;indexOf 判斷字符或者子字符串出現的位置;contains 是否包含子字符串;replaceAll 替換所有的 ,replaceFirst 只替換第一個;
public class TestString {public static void main(String[] args) {// TODO Auto-generated method stubString sentence = "蓋倫,在進行了連續8次擊殺后,獲得了 超神 的稱號";char c = sentence.charAt(0);System.out.println(c); //輸出 蓋char[] cs = sentence.toCharArray(); //獲取對應的字符數組System.out.println(sentence.length() == cs.length); //截取從第3個開始的字符串 (基0)//到5-1的位置的字符串//左閉右開String subString2 = sentence.substring(3,5);System.out.println(subString2);//根據,進行分割,得到3個子字符串String subSentences[] = sentence.split(",");for (String sub : subSentences) {System.out.println(sub);}System.out.println(sentence.indexOf('8')); //字符第一次出現的位置System.out.println(sentence.indexOf("超神")); //字符串第一次出現的位置System.out.println(sentence.lastIndexOf("了")); //字符串最后出現的位置System.out.println(sentence.indexOf(',',5)); //從位置5開始,出現的第一次,的位置 System.out.println(sentence.contains("擊殺")); //是否包含字符串"擊殺"String temp = sentence.replaceFirst(",","");//只替換第一個System.out.println(temp);}}?
11、比較字符串:
public class TestString {public static void main(String[] args) {// TODO Auto-generated method stubString str="the light"; //編譯器碰到字符串的字面值就會創建一個新對象String str2=new String();String str3="the light"; //當發現已經存在的字符串對象就不會重復創建System.out.println(str==str2); //falseSystem.out.println(str==str3); //trueSystem.out.println(str.equals(str2)); //false,完全一樣則返回trueString str4=str3.toUpperCase();System.out.println(str.equalsIgnoreCase(str4)); //trueString start="th";String end="ight";System.out.println(str.startsWith(start));//true,是否以字符串開始或結束System.out.println(str.endsWith(end));}}?
11、StringBuffer可變長的字符串,有以下方法
public static void main(String[] args) {String str="the";StringBuffer sb=new StringBuffer(str);System.out.println(str.length()); //3,String內部是一個字符數組System.out.println(sb.capacity()); //19,內部也有一個字符數組,留有冗余數組,19這個空間大小,不同JDK不一樣sb.append(" Man"); //追加sb.insert(7," IS BOY"); //插入sb.reverse(); //反轉System.out.println(sb); }?
12、Date類:注意:是java.util.Date;?而非 java.sql.Date,此類是給數據庫訪問的時候使用的
時間原點概念:Java中的時間原點,其對應的日期是1970年1月1日 8點0分0秒 。
?
public static void main(String[] args) {Date d1=new Date(); //創建日期對象System.out.println("當前日期時間是"+d1);// 從1970年1月1日 早上8點0分0秒 開始經歷的毫秒數Date d2 = new Date(5000);System.out.println("從1970年1月1日 早上8點0分0秒 開始經歷了5秒的時間");System.out.println(d2);//getTime()方法得到一個long型的整數System.out.println("從時間原點開始經歷的毫秒數:"+d1.getTime());//new Date().getTime() 和 System.currentTimeMillis() 基本是一樣的System.out.println("系統的當前毫秒數:"+System.currentTimeMillis());}?
13、SimpleDateFormat 日期格式化類,有以下方法
public static void main(String[] args) {//日期轉字符串//y 代表年//M 代表月//d 代表日//H 代表24進制的小時//h 代表12進制的小時//m 代表分鐘//s 代表秒//S 代表毫秒SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS" );Date d= new Date();String str = sdf.format(d);System.out.println("當前時間通過 yyyy-MM-dd HH:mm:ss SSS 格式化后的輸出: "+str);//字符串轉日期SimpleDateFormat sdf2 =new SimpleDateFormat("yyyy/MM/dd HH:mm:ss" );String str2 = "2016/1/5 12:12:12";//需要進行異常處理try {Date d2 = sdf2.parse(str2);System.out.printf("字符串 %s 通過格式 yyyy/MM/dd HH:mm:ss %n轉換為日期對象: %s",str2,d2.toString());} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}}14、日歷對象,采用單例模式獲取日歷對象Calendar.getInstance();
public static void main(String[] args) {Calendar c = Calendar.getInstance();Date now = c.getTime();// 當前日期System.out.println("當前日期:\t" + format(c.getTime()));// 下個月的今天c.setTime(now);c.add(Calendar.MONTH, 1);System.out.println("下個月的今天:\t" +format(c.getTime()));// 去年的今天c.setTime(now);c.add(Calendar.YEAR, -1);System.out.println("去年的今天:\t" +format(c.getTime()));// 上個月的第三天c.setTime(now);c.add(Calendar.MONTH, -1);c.set(Calendar.DATE, 3);System.out.println("上個月的第三天:\t" +format(c.getTime()));}?
更多資源或實戰項目詳細可以了解:http://how2j.cn/k/interface-inheritance/interface-inheritance-practise/679.html?p=29570
總結
以上是生活随笔為你收集整理的java基础学习笔记(三)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 趣学python3(25)-del,de
- 下一篇: 趣学python3(26)-pygame