本文重在溫習……不過初學以及進階高手不可錯過
1. public static void arraycopy(全小寫)(object src,int srcPos,object dest,int destPos,int length)

1 package b; 2 /* 3 * 使用java.lang.System類的靜態方法,使用for循環一個一個拷貝會很慢,由於數組 4 * 在內存里往往都是連續的區域,因此最有效率的往往是直接拷貝內存。 5 * public static void arraycopy(全小寫)(object src,int srcPos,object dest,int destPos,int length) 6 * 如果超過目標數組的邊界,則會拋出數組越界異常。 7 */ 8 public class ArrayCopy { 9 //沒加上String args[]時運行的話還是前一個運行過的程序的結果。 10 public static void main(String args[]) { 11 String src[] = {"Microsoft","IBM","Sun","Oracle"}; 12 String dest[]= new String[6]; 13 System.arraycopy(src,0,dest,0,src.length); 14 //拷貝是並不是真的真考,而是dest數組在堆里也指向那幾個公司,那幾個公司在堆內存里還是只有一份。 15 for(int i=0; i<dest.length; i++) { 16 System.out.println(dest[i]);//會打印null值 17 18 } 19 System.out.println("----------------"); 20 int a[][] = {{1,2},{1,2,3},{3,4}};//里面還是用大括號不是小括號 21 int b[][] = new int[3][];//此時第一維里是null,第二維里才是0 22 System.arraycopy(a,0,b,0,a.length); 23 /* 24 * 原數組的內容在堆內存里還是只有一份不是兩份,由於指向的是同一塊內存, 25 * 因此對dest的操作相當於對src的操作。 26 */ 27 b[2][1] = 100; 28 for(int i=0; i<a.length; i++) { 29 for(int j=0; j<a[i].length; j++) { 30 System.out.println(a[i][j]); 31 } 32 } 33 System.out.println("---OK---"); 34 35 } 36 }
2.二分查找

1 /* 2 * 二分查找某個數的位置 3 */ 4 package b; 5 6 public class BinaryFind { 7 public static void main(String[] args) { 8 int[] a = new int[100]; 9 //省去排序的步驟 10 for(int i=0; i<a.length; i++) { 11 a[i] = i*i; 12 } 13 int res = 64;//待查找的數 14 int pos = search(a,res); 15 System.out.println(pos);//返回的實際上是下標 16 } 17 public static int search(int[] a,int num) { 18 if(a.length == 0) { 19 return -1; 20 } 21 int start = 0; 22 int end = a.length - 1; 23 int mid = (start + end)/2;//和不能溢出 24 while(start<end) { 25 if(num == a[mid]) { 26 return mid; 27 }else if(num>a[mid]) { 28 start = mid +1; 29 }else { 30 end = mid -1; 31 } 32 mid = (start + end)/2; 33 } 34 return -1; 35 } 36 37 }
3.正則表達式

1 package b; 2 3 import java.util.Calendar; 4 import java.util.regex.Matcher; 5 import java.util.regex.Pattern; 6 7 public class Calender { 8 public static void main(String[] args) { 9 Pattern p = Pattern.compile("(\\d\\d)\\1"); 10 /* 11 * 輸出true,\\1表示和第一個組的一樣,若改成1213就不對了; 12 * 若是Pattern.compile("(\\d(\\d))\\2")則需改成122才對 13 * 14 */ 15 16 String s = "1212"; 17 Matcher m = p.matcher(s); 18 System.out.println(m.matches()); 19 20 } 21 22 }
4.統計代碼里多少空行,注釋行,程序行

1 package b; 2 3 /* 4 * 統計代碼里多少空行,注釋行,程序行 5 * 實際上使用String里的startsWith和endsWith也行. 6 * 若是項目經理用的話還要統計每行的字符數是否以{;結尾,防止偷懶 7 */ 8 import java.io.BufferedReader; 9 import java.io.File; 10 import java.io.FileNotFoundException; 11 import java.io.FileReader; 12 import java.io.IOException; 13 14 public class CoderCount { 15 16 static long normalLines = 0; 17 static long commentLines = 0; 18 static long whiteLines = 0; 19 20 public static void main(String[] args) { 21 File f = new File("D:\\share\\src"); 22 File[] codeFiles = f.listFiles(); 23 for(File child : codeFiles){ 24 //.java$表示以“.java”結尾 25 if(child.getName().matches(".*\\.java$")) { 26 solve(child); 27 } 28 } 29 30 System.out.println("normalLines:" + normalLines); 31 System.out.println("commentLines:" + commentLines); 32 System.out.println("whiteLines:" + whiteLines); 33 34 } 35 36 private static void solve(File f) { 37 BufferedReader br = null; 38 boolean comment = false; 39 try { 40 br = new BufferedReader(new FileReader(f)); 41 String line = ""; 42 while((line = br.readLine()) != null) { 43 /* 44 * //有的注釋行前面有一個tab 45 * 不可寫在readLine后 46 * 最后一行的話會空指針 47 */ 48 line = line.trim(); 49 //readLine讀出字符串后就把后面的換行去掉啦 50 // 小寫的s,\s表示空白字符,大寫的表示非空白字符 51 if(line.matches("^[\\s&&[^\\n]]*$")) {//^表示行開頭 52 whiteLines ++; 53 } else if (line.startsWith("/*") && !line.endsWith("*/")) { 54 commentLines ++; 55 comment = true; 56 } else if (line.startsWith("/*") && line.endsWith("*/")) { 57 commentLines ++; 58 } else if (true == comment) { 59 commentLines ++; 60 if(line.endsWith("*/")) { 61 comment = false; 62 } 63 } else if (line.startsWith("//")) { 64 commentLines ++; 65 } else { 66 normalLines ++; 67 } 68 } 69 } catch (FileNotFoundException e) { 70 e.printStackTrace(); 71 } catch (IOException e) { 72 e.printStackTrace(); 73 } finally { 74 if(br != null) { 75 try { 76 br.close(); 77 br = null; 78 } catch (IOException e) { 79 e.printStackTrace(); 80 } 81 } 82 } 83 } 84 85 }
5.面向對象思路解決約瑟夫問題

1 package b; 2 3 /*面向對象的思路可以代替算法,先考慮有幾個類,再考慮各個類的屬性和方法,方法先考慮構造方法(考慮別人會怎么用就怎么設計)。 4 * 實際上相當於鏈表 5 */ 6 //有個小問題,馬士兵的兩個類都沒有加static就行了,我的卻必須加,否則CE 7 public class Count3Quit1 { 8 public static void main(String[] args) { 9 KidCircle kc = new KidCircle(500); 10 int num = 0; 11 Kid k = kc.first; 12 while(kc.count>1) { 13 num++; 14 if(num==3) { 15 num=0; 16 kc.delete(k); 17 } 18 k = k.right; 19 } 20 System.out.println(kc.first.id+1); 21 } 22 static class Kid { 23 int id; 24 Kid left; 25 Kid right; 26 27 } 28 29 static class KidCircle { 30 int count = 0;//剛開始是空圈 31 Kid first, last; 32 33 //表示幾個人的圈,考慮別人怎么用,咱就怎么寫 34 KidCircle(int n) { 35 for(int i=0; i<n; i++) { 36 add(); 37 } 38 } 39 40 /*我們往圈里添加小孩,賓語就是往往就是參數,也可以不要參數 41 * 在末尾添加小孩 42 */ 43 void add() { 44 Kid k = new Kid(); 45 k.id = count; 46 if(count <=0) { 47 first = k; 48 last = first; 49 k.left = k; 50 k.right = k; 51 }else { 52 last.right = k; 53 k.left = last; 54 k.right = first; 55 first.left = k; 56 last = k; 57 } 58 count++; 59 60 } 61 62 //雙向循環鏈表 63 void delete(Kid k) { 64 if(count <= 0) { 65 return ; 66 }else if(count == 1) { 67 first = last = null; 68 }else { 69 k.left.right = k.right; 70 /* 71 * 垃圾收集器會回收k 72 */ 73 k.right.left = k.left; 74 if(k == first) { 75 first = k.right; 76 }else if(k == last) { 77 last = k.left; 78 } 79 } 80 count--; 81 } 82 } 83 }
6.默認打印Date格式

1 package b; 2 3 import java.util.Date; 4 5 public class Ke { 6 7 public static void main(String[] args) { 8 Date date = new Date(); 9 System.out.println(date); 10 } 11 } 12 //結果:Thu Jul 11 23:56:07 CST 2013
7.new子類

1 package b; 2 3 import java.util.Scanner; 4 5 /* 6 * 由下面這個簡短的程序可以看出,父類只要是無參構造方法,那么在new子類的時候就會自動調用 7 */ 8 public class T { 9 static String ch; 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 //Scanner in = new Scanner(System.in); 13 //String s = in.next(); 14 String s = "a"; 15 new F(); 16 //若是直接把s賦值為a,那么下面為true,通過scanner讀入的話為false 17 System.out.println(s=="a"); 18 19 } 20 } 21 class F { 22 F() { 23 System.out.println("你好"); 24 } 25 } 26 27 class S extends F { 28 29 } 30 /* 31 * 你好 32 true 33 */
8.正則表達式的知識都忘啦

1 import java.util.regex.Matcher; 2 import java.util.regex.Pattern; 3 4 public class Te { 5 6 public static void main(String[] args) { 7 8 /* 9 * 分別加上小括號,不算最外邊的大括號,第一個左括號便是第一組 10 */ 11 Pattern p = Pattern.compile("(\\d{3,5})([a-z]{2})"); 12 String s = "123aaa-77878bb-646dd-00"; 13 Matcher m = p.matcher(s); 14 while(m.find()) { 15 System.out.println(m.group()); 16 System.out.println(m.group(1));//輸出每對符合的 數字 17 System.out.println(m.group(2));//輸出每對符合的 字母 18 } 19 } 20 }
9.采用indexOf方法統計子串出現次數

1 package b; 2 3 /* 4 * 統計子串出現次數 5 */ 6 public class SubstrNum { 7 public static void main(String[] args) { 8 String str = "hajavakjhjdkjavakjhkjhkjavakajakajavakllk"; 9 String substr = "java"; 10 int index = -1; 11 int num = 0; 12 while((index=str.indexOf(substr))!=-1) { 13 num++; 14 //數組的length方法不加括號 15 str = str.substring(index + substr.length()); 16 } 17 System.out.println(num); 18 System.out.println("----ok-----"); 19 } 20 21 }
10.改進選擇排序實現日期排序

1 package b; 2 3 /* 4 * 就因為數組多分配了,就一直空指針異常 5 */ 6 public class MyDate { 7 public static void main(String[] args) { 8 9 /* 10 * 必須開辟四個空間,不能大於,否則空指針異常 11 * 若是10,則array.length也為10,當然空指針異常 12 */ 13 DateComp[] array = new DateComp[4]; 14 array[0] = new DateComp(2010,8,23); 15 array[1] = new DateComp(2013,8,23); 16 array[2] = new DateComp(2010,9,23); 17 array[3] = new DateComp(2010,8,25); 18 compare(array);//不用加類名就行 19 for(int i=0; i<array.length; i++) 20 System.out.println(array[i]); 21 } 22 public static void compare(DateComp[] a) { 23 for(int i=0; i<a.length; i++) { 24 int k = i; 25 //比較次數不變,,每次最多交換一次 26 for(int j=k+1; j<a.length; j++) { 27 if(a[j].comp(a[k])==-1)//說明a[j]大,進行由大到小排序 28 k = j; 29 } 30 if(k!=i) { 31 DateComp temp = a[k]; 32 a[k] = a[i]; 33 a[i] = temp; 34 } 35 } 36 } 37 } 38 class DateComp { 39 int year; 40 int month; 41 int day; 42 DateComp(int y, int m, int d) { 43 year = y; month = m; day = d; 44 } 45 public int comp(DateComp d) { 46 if(d.year>year) 47 return 1; 48 else if(d.month >month) 49 return 1; 50 else if(d.day>day) 51 return 1; 52 else 53 return -1; 54 } 55 public String toString() { 56 return "Year:Month:Day --" + year + "-" +month+"-" + day; 57 } 58 }
11.HashMap

1 package b; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 //需要命令行參數 7 public class MapStatistics { 8 private static final Integer ONE = new Integer(1); 9 public static void main(String[] args) { 10 Map m = new HashMap(); 11 for(int i=0; i<args.length; i++) { 12 Integer freq = (Integer)m.get(args[i]); 13 //freq肯定是null,因為4 5 6 都沒有對應的value值,一直迷惑在這了 14 if(freq == null) { 15 m.put(args[i],ONE); 16 }else { 17 m.put(args[i],new Integer(freq.intValue() + 1)); 18 } 19 } 20 System.out.println(m.size() + " distinct words detected"); 21 System.out.println(m); 22 } 23 24 } 25 26 /* 27 * 輸入 4 5 6 28 * 輸出 29 * 3 distinct words detected 30 * {6=1, 5=1, 4=1} 31 */
12.事件監聽

1 package b; 2 3 import javax.swing.*; 4 import java.awt.*; 5 import java.awt.event.*; 6 public class FrameDemo 7 { 8 //定義該圖形中所需的組件的引用 9 private Frame f; 10 private Button bt; 11 12 //方法 13 FrameDemo()//構造方法 14 { 15 madeFrame(); 16 } 17 18 public void madeFrame() 19 { 20 f = new Frame("My Frame"); 21 22 //對Frame進行基本設置。 23 f.setBounds(300,100,600,500);//對框架的位置和大小進行設置 24 f.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));//設計布局 25 26 bt = new Button("My Button"); 27 28 //將組件添加到Frame中 29 f.add(bt); 30 31 //加載一下窗體上的事件 32 myEvent(); 33 34 //顯示窗體 35 f.setVisible(true); 36 } 37 38 private void myEvent() 39 { 40 f.addWindowListener(new WindowAdapter()//窗口監聽 41 { 42 public void windowClosing(WindowEvent e) 43 { 44 System.out.println("窗體執行關閉!"); 45 System.exit(0); 46 } 47 }); 48 //讓按鈕具備關閉窗口的功能 49 bt.addActionListener (new ActionListener() 50 { 51 public void actionPerformed(ActionEvent e) 52 { 53 System.out.println("按鈕執行關閉窗口的功能"); 54 System.exit(0); 55 } 56 }); 57 } 58 59 public static void main(String[] agrs) 60 { 61 new FrameDemo(); 62 } 63 }
13.split

1 package b; 2 3 /* 4 * 判斷一個正整數是幾位數在while循環里不斷除以10,直到商為0 5 * 或者轉換為字符串只需求出長度即可。 6 */ 7 public class TestSplit { 8 public static void main(String[] args) { 9 int j = 1234567; 10 String strNum = String.valueOf(j); 11 System.out.println("j是"+strNum.length()+"位數"); 12 13 String s = "Mary,F,1978"; 14 String[] str = s.split(",");//注意參數是String類型的正則表達式,所以是雙引號 15 for(int i=0; i<str.length; i++) {//length不帶括號 16 System.out.println(str[i]); 17 } 18 System.out.println("-------ok--------"); 19 } 20 21 }
14. 多維數組

1 package b; 2 /* 3 * Java中的多維數組和C/C++不同,不一定是每行長度一樣,必須從左到右聲明, 4 *即int a[][] = new int[3][]可以,但是int a[][] = new int[][4]不行, 5 *因為java中二維數組看成以數組為元素的數組,前一維不存在的話,沒法分配下一維內存。 6 * Int a[3][2] = {(1,2),(5,5),(6,8)}這樣寫非法, 7 * 執行靜態初始化時不該指定維度,防止出錯。 8 */ 9 public class TestString { 10 public static void main(String args[]) { 11 String s[][];//執行動態初始化時分為兩步走,第一步時任何一維都不可指定 12 s = new String[3][]; 13 s[0] = new String[2]; 14 s[1] = new String[3]; 15 s[2] = new String[2]; 16 for(int i=0; i<s.length; i++) { 17 for(int j=0; j<s[i].length; j++) { 18 s[i][j] = new String("我的位置是:"+i+","+j);//可以直接寫常量字符串 19 } 20 } 21 for(int i=0; i<s.length; i++) { 22 for(int j=0; j<s[i].length; j++) { 23 System.out.println(s[i][j]); 24 } 25 } 26 } 27 }
15.equals

1 package b; 2 3 public class TestStringEqual { 4 public static void main(String[] args) { 5 /* 6 * s1中的hello分配在data segement,s1在棧區,java虛擬機會對 7 * data segement進行優化,所以s3指向的也是這個內存 8 * 9 */ 10 String s1 = "hello"; 11 String s2 = "world"; 12 String s3 = "hello"; 13 System.out.println(s1==s3);//true 14 /* 15 * s1中的hello分配在堆,s1在棧區,s2的也分配在堆區但是不同的內存 16 * 引用不同,所以第一個是false。 17 * equals是System類的靜態方法,在Object類中。 18 */ 19 s1 = new String("hello"); 20 s2 = new String("hello"); 21 System.out.println(s1==s2);//false 22 System.out.println(s1.equals(s2));//true 23 24 char c[] = {'s','u','n',' ','j','a','v','a'}; 25 String s4 = new String(c); 26 String s5 = new String(c,4,4);//由結果可與看出第二個4是下標 27 System.out.println(s4);//sun java 28 System.out.println(s5);//java 29 System.out.println("--------ok---------"); 30 } 31 32 }
16.String內存解析和StringBuffer

1 package b; 2 3 /* 4 * 5 String是不可變的字符序列 6 對於”String s1 = "123";String s2 = "456";s1 += s2;”s1.charAt(1)= '8'是錯誤的, 7 但是s1 += s2是可以的(在內存里並不是把s2放於s1的內存后面(這樣的話就違背了不可變的性質), 8 而是開辟一個(s1 + s2)大小的內存再把s1和s2分別拷貝過去), 9 也可以刪除字符串(比如substring方法), 10 刪除中間的字符串的話也是分別把兩頭拷貝到新內存里再指向新內存,因此效率很低,就產生了StringBuffer 11 */ 12 public class TestStringBuffer { 13 public static void main(String[] args) { 14 String s1 = "123"; 15 String s2 = "456"; 16 s1 += s2; 17 System.out.println(s1); 18 19 StringBuffer sb = new StringBuffer(s1); 20 //由於append方法返回的仍然是StringBuffer,所以后面可以繼續使用append方法 21 sb.append("/").append("sun").append("/").append("Oracle"); 22 System.out.println(sb); 23 24 StringBuffer sb1 = new StringBuffer("數字"); 25 for(int i=0; i<9; i++) { 26 sb1.append(i); 27 } 28 System.out.println(sb1); 29 30 //delete方法:起始和結束; 31 sb1.delete(8, sb1.length()).insert(0,"abc"); 32 System.out.println(sb1); 33 System.out.println(sb1.reverse()); 34 35 System.out.println("----ok-----"); 36 } 37 38 }
17.Set

1 package b; 2 3 import java.util.*; 4 5 /* 6 * set包括hashset和treeset,其中元素無順序和不重復 7 * 和數學上的集合對應 8 */ 9 public class TestSet { 10 public static void main(String[] args) { 11 Set<Object> s = new HashSet();//若是import java.util.Set就CE 12 s.add("hello"); 13 s.add(new OtherName("f1","f2")); 14 /* 15 * 由於在OtherName里重寫了equals方法,所以 16 * 下面的這一對象相當於同一個元素,不會被加入 17 */ 18 s.add(new OtherName("f1","f2")); 19 System.out.println(s); 20 21 Set s1 = new HashSet(); 22 Set s2 = new HashSet(); 23 s1.add("a"); s1.add("b"); s1.add("d"); 24 s2.add("a"); s2.add("c"); s2.add("d"); 25 Set sn = new HashSet(s1); 26 sn.retainAll(s2);//求交集 27 Set su = new HashSet(s1);//因為sn已經變化 28 su.addAll(s2);//並集 29 System.out.println(sn); 30 System.out.println(su); 31 } 32 33 } 34 35 class OtherName { 36 private String firstName,lastName; 37 public OtherName(String firstName,String lastName) { 38 this.firstName = firstName; 39 this.lastName = lastName; 40 } 41 public String getFirstName() { 42 return firstName; 43 } 44 public void setFirstName(String firstName) { 45 this.firstName = firstName; 46 } 47 public String getLastName() { 48 return lastName; 49 } 50 public void setLastName(String lastName) { 51 this.lastName = lastName; 52 } 53 54 //小馬說的,這是最簡單的 55 public int hashCode() { 56 return firstName.hashCode(); 57 } 58 //這個是小馬寫的,以前沒太懂,現在懂了 59 public boolean equals(Object obj) { 60 if(obj instanceof OtherName) { 61 OtherName other = (OtherName)obj; 62 return firstName.equals(other.firstName) 63 && lastName.equals(other.lastName); 64 } 65 return super.equals(obj); 66 } 67 public String toString() { 68 return firstName + " " + lastName; 69 } 70 71 }
18.內部類

1 package b; 2 3 public abstract class Week { 4 private Week(){ 5 6 } 7 8 //由於是abstract不可以直接new對象,但是可以經由子類,此處采用內部類 9 public static final Week sun = new Week() { 10 11 @Override 12 public Week nextDay() { 13 // TODO Auto-generated method stub 14 return mon; 15 } 16 17 18 };//必須加分號 19 20 public static final Week mon = new Week() { 21 22 @Override 23 public Week nextDay() { 24 // TODO Auto-generated method stub 25 return sun; 26 } 27 28 }; 29 30 public abstract Week nextDay();//必須加上abstract,否則總提示需要返回值 31 32 //抽象類中可以有非抽象方法,子類實現該類的時候可以不重寫該方法 33 public String toString() { 34 return this==sun?"Sunday":"Monday"; 35 } 36 37 }
19.Map

1 package b; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 import java.util.TreeMap; 6 7 /* 8 * Map有hashmap和treemap(紅黑樹), 9 * key不可重復(仍然是equals,一個一個比較又太麻煩, 10 * 因此比較的是hashCode,需要重寫hashCode方法), 11 * 使用put(key,value)返回了Object是原來的 12 * value,get(key),size(),containsKey 13 * 和containsValue,map里的key和value必須都是對象, 14 * 至少要分配在堆,但是JDK1.5以后這樣也是可以的map.put(“one”,1)而不必map.put(“one”,Integer(1)) 15 * 里面會自動打包(將基本類型轉換為包裝類)。 16 */ 17 public class TestMap { 18 public static void main(String[] args) { 19 Map m1 = new HashMap(); 20 Map m2 = new TreeMap(); 21 m1.put("one", 1); 22 m1.put("one", new Integer(1));//這兩種寫法等價,內存里實際上都是第二種 23 m1.put("one", 1); 24 m1.put("two", new Integer(2));//仍然要加上new 25 m1.put("A", 1); 26 m1.put("B", new Integer(2)); 27 System.out.println(m1.size()); 28 System.out.println(m1.containsKey("one")); 29 System.out.println(m1.containsValue(2)); 30 31 if(m1.containsKey("two")) { 32 //這兩種寫法等價 33 //int i = m1.get("two").intValue(); 34 int i = (Integer)m1.get("two");//必須加上強轉才可自動解包,否則鬼知道能否轉為int類型 35 System.out.println("在m1中two的value為:" + i); 36 } 37 38 Map m3 = new HashMap(m1); 39 m3.putAll(m2); 40 System.out.println(m3); 41 System.out.println("----------ok----------"); 42 } 43 44 }
20.Collections類

1 package b; 2 3 import java.util.*; 4 5 /* 6 * Collections是類,類方法有shuffle(容器)表示隨機排序, 7 * reverse表示逆序(ArrayLIst還是用數組實現的, 8 * 需要拷貝,而LinkedList直接變換指針就好了), 9 * sort排序,binarySearch(容器,元素)是折半查找。 10 */ 11 public class TestList { 12 public static void main(String[] args) { 13 List a = new LinkedList(); 14 for(int i=0; i<9; i++) { 15 a.add("a"+i); 16 } 17 System.out.println(a); 18 Collections.shuffle(a); 19 System.out.println(a); 20 Collections.sort(a); 21 System.out.println(a); 22 Collections.reverse(a); 23 System.out.println(a); 24 Collections.sort(a);//折半查找的前提是有序,返回的是下標 25 System.out.println(Collections.binarySearch(a, "a5")); 26 System.out.println("\n"); 27 } 28 } 29 /* 30 * 上面的算法如何確定“大小”順序呢,所有可以排序的類都實現了 31 * java.lang.Comparable接口,該接口中只有一個方法 32 * public int compareTo(Object obj),該方法返回0表示this == obj, 33 * 正數表示this>obj,里面是Object類型,現在是泛型,使用了泛型后 34 * 比較的兩者就肯定有意義,不會出來貓和超人比。 35 */
21.Integer

1 package b; 2 /* 3 * 基本數據類型包裝類(包裝成對象分配在堆內存):在java.lang包, 4 * 里面都有MAX_VALUE,MIN_VALUE,和SIZE, 5 * 用於各種數之間的轉換,查看API。 6 */ 7 public class TestInteger { 8 public static void main(String[] args) { 9 Integer i = new Integer("100");//分配在堆上 10 Double d = new Double("123.456"); 11 int j = i.intValue() + d.intValue(); 12 float f = i.floatValue() + d.floatValue(); 13 System.out.println(j); 14 System.out.println(f); 15 16 double pi = Double.parseDouble("3.1415926"); 17 double r = Double.valueOf("2.0").doubleValue(); 18 double s= pi*r*r; 19 System.out.println(s); 20 21 try { 22 int k = Integer.parseInt("1.25"); 23 k += 1; 24 }catch (NumberFormatException e) { 25 System.out.println("數據格式不對"); 26 //e.printStackTrace(); 27 } 28 29 System.out.println(Integer.toBinaryString(123)+"B"); 30 System.out.println(Integer.toHexString(123)+"H"); 31 System.out.println(Integer.toOctalString(123)+"O");//八進制 32 System.out.println("---------ok------------"); 33 } 34 35 }
22.iterator

1 package b; 2 3 import java.util.*; 4 5 /* 6 * Collections是類,包含shuffle,sort,binarySearch 7 */ 8 public class TestIterator { 9 public static void main(String[] args) { 10 11 Collection c = new HashSet(); 12 c.add(new MyName("first","last")); 13 c.add(new MyName("first1","last1")); 14 c.add(new MyName("first2","last2")); 15 //注意iterator在javax里也有,但此處需要用util包里的 16 Iterator itr = c.iterator(); 17 ////打印出來的順序不確定,因為set本身便是沒有順序 18 while(itr.hasNext()) { 19 MyName name = (MyName)itr.next(); 20 System.out.println(name.getFirstName()); 21 } 22 /* 23 * Iterator中的remove方法是遍歷過程中的唯一刪除元素的安全方法, 24 * (因為iterator在遍歷過程中執行了鎖定(線程的東西)和數據庫 25 * 事務與鎖里的類似) 26 * 具體的容器set和list由於實現了collection接口所以也有remove方法, 27 * 但是不安全。 28 */ 29 for(Iterator i=c.iterator(); i.hasNext();) { 30 MyName name = (MyName)i.next(); 31 if(name.getFirstName()=="first") { 32 i.remove();//使用c.remove(name)會產生例外 33 } 34 } 35 System.out.println("------ok-------"); 36 } 37 38 } 39 40 class MyName { 41 private String firstName,lastName; 42 public MyName(String firstName,String lastName) { 43 this.firstName = firstName; 44 this.lastName = lastName; 45 } 46 public String getFirstName() { 47 return firstName; 48 } 49 public void setFirstName(String firstName) { 50 this.firstName = firstName; 51 } 52 public String getLastName() { 53 return lastName; 54 } 55 public void setLastName(String lastName) { 56 this.lastName = lastName; 57 } 58 59 //小馬說的,這是最簡單的 60 public int hashCode() { 61 return firstName.hashCode(); 62 } 63 //這個是小馬寫的,沒看太懂 64 public boolean equals(Object obj) { 65 if(obj instanceof MyName) { 66 MyName other = (MyName)obj; 67 return firstName.equals(other.firstName) 68 && lastName.equals(other.lastName); 69 } 70 return super.equals(obj); 71 } 72 73 }
23.HashSet

1 package b; 2 3 import java.util.*; 4 /* 5 * 相等的對象有相同的hash codes 6 * 通過hash codes可以再內存里找對象,但不是具體的物理地址 7 * 比如查字典時目錄就是索引,通過目錄找到值就是鍵,因此hash codes 8 * 常用來做索引,比如在map里。涉及索引時需要重寫equals和hashcode 9 */ 10 public class TestHashSet { 11 12 public static void main(String[] args) { 13 Collection c = new HashSet(); 14 c.add("hello"); 15 c.add(new Name("first","last")); 16 c.add(new Integer(100)); 17 /* 18 * remove方法返回boolean值,既可以不 19 * 賦值給一個boolean變量,也可以賦值給。比如下面的即可以直接調用 20 * 也可以調用后打印出來,有點小迷惑。 21 */ 22 c.remove("hello");//可以刪除掉 23 c.remove(new Integer(100));//也可以刪除掉,因為Integer重寫了equals方法 24 System.out.println(c.remove(new Name("first","last"))); 25 System.out.println(c); 26 } 27 } 28 class Name { 29 30 private String firstName,lastName; 31 public Name(String firstName,String lastName) { 32 this.firstName = firstName; 33 this.lastName = lastName; 34 } 35 public String getFirstName() { 36 return firstName; 37 } 38 public void setFirstName(String firstName) { 39 this.firstName = firstName; 40 } 41 public String getLastName() { 42 return lastName; 43 } 44 public void setLastName(String lastName) { 45 this.lastName = lastName; 46 } 47 /* (non-Javadoc) 48 * @see java.lang.Object#hashCode() 49 */ 50 @Override 51 /* 52 public int hashCode() { 53 final int prime = 31; 54 int result = 1; 55 result = prime * result 56 + ((firstName == null) ? 0 : firstName.hashCode()); 57 result = prime * result 58 + ((lastName == null) ? 0 : lastName.hashCode()); 59 return result; 60 } 61 */ 62 //小馬說的,這是最簡單的 63 public int hashCode() { 64 return firstName.hashCode(); 65 } 66 /* (non-Javadoc) 67 * @see java.lang.Object#equals(java.lang.Object) 68 */ 69 @Override 70 /*這是java自動生成的,比較繁瑣 71 public boolean equals(Object obj) { 72 if (this == obj) { 73 return true; 74 } 75 if (obj == null) { 76 return false; 77 } 78 if (!(obj instanceof Name)) { 79 return false; 80 } 81 Name other = (Name) obj; 82 if (firstName == null) { 83 if (other.firstName != null) { 84 return false; 85 } 86 } else if (!firstName.equals(other.firstName)) { 87 return false; 88 } 89 if (lastName == null) { 90 if (other.lastName != null) { 91 return false; 92 } 93 } else if (!lastName.equals(other.lastName)) { 94 return false; 95 } 96 return true; 97 } 98 */ 99 public boolean equals(Object obj) { 100 if(obj instanceof Name) { 101 Name other = (Name)obj; 102 return firstName.equals(other.firstName) 103 && lastName.equals(other.lastName); 104 } 105 return super.equals(obj); 106 } 107 }

1 package b; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 import java.util.HashSet; 6 7 public class Reflect { 8 9 public static void main(String[] args) { 10 /* 11 * new ArrayList()的話不論是否重寫hashCode和equals都輸出5; 12 * new HashSet()重寫前是4,后是3 13 */ 14 //Collection coll = new ArrayList(); 15 Collection coll = new HashSet(); 16 Pointer p1 = new Pointer(1, 1); 17 Pointer p2 = new Pointer(1, 1); 18 Pointer p3 = new Pointer(3, 3); 19 Pointer p4 = new Pointer(4, 4); 20 21 coll.add(p1); 22 coll.add(p2); 23 coll.add(p3); 24 coll.add(p4); 25 coll.add(p4); 26 /* 27 * 參與hashCode運算的值,在加載后就不應該再改動,否則刪除的話是刪不掉的(不會報錯),這就是內存泄露 28 */ 29 System.out.println(coll.size()); 30 } 31 } 32 33 class Pointer { 34 public int x = 0; 35 public int y = 0; 36 37 public Pointer(int x, int y) { 38 super(); 39 this.x = x; 40 this.y = y; 41 } 42 43 @Override 44 public int hashCode() { 45 final int prime = 31; 46 int result = 1; 47 result = prime * result + x; 48 result = prime * result + y; 49 return result; 50 } 51 52 @Override 53 public boolean equals(Object obj) { 54 if (this == obj) 55 return true; 56 if (obj == null) 57 return false; 58 if (getClass() != obj.getClass()) 59 return false; 60 Pointer other = (Pointer) obj; 61 if (x != other.x) 62 return false; 63 if (y != other.y) 64 return false; 65 return true; 66 } 67 }
24.創建File

1 package b; 2 3 import java.io.File; 4 import java.io.IOException; 5 /* 6 * 若是class文件在包中, 7 * 運行后其父路徑(父路徑是class文件的父路徑)是包的父路徑, 8 * 創建的目錄(目錄也是一種文件)和包路徑的上一個平級不和包平級,試試eclips就看出來了 9 */ 10 public class TestFile { 11 public static void main(String[] args) { 12 String separator = File.separator;//不管在wins還是linux下都可以用正斜杠(反斜杠是轉義字符) 13 String filename = "myfile.txt"; 14 String directory = "mydir1" + separator + "myfile2"; 15 //下面這兩種寫法也行 16 //String directory = "mydir1/myfile2"; 17 //String directory = "mydir1\\myfile2";//一個反斜杠是轉義字符 18 File f = new File(directory,filename);//現在只是內存里的一個對象 19 if(f.exists()) { 20 System.out.println("文件名:" + f.getAbsolutePath()); 21 System.out.println("文件大小:" + f.length()); 22 }else { 23 //父路徑是class文件的父路徑 24 f.getParentFile().mkdirs();//因為是兩個"mydir1/myfile2",所以加s了 25 try { 26 f.createNewFile(); 27 }catch (IOException e) { 28 e.printStackTrace(); 29 } 30 } 31 32 } 33 34 }
25.枚舉+內部類實現交通燈

1 package b; 2 3 import java.util.Date; 4 5 class TestEnum { 6 public enum TraficLamp { 7 //Red,Green,Yellow; 8 Red(30) {//new子類的對象並調用父類的有參構造方法 9 10 @Override 11 public TraficLamp nextLamp() { 12 // TODO Auto-generated method stub 13 return Green; 14 } 15 },//必須加逗號 16 17 Green(45) { 18 19 @Override 20 public TraficLamp nextLamp() { 21 // TODO Auto-generated method stub 22 return Yellow; 23 } 24 25 },//必須加逗號 26 27 Yellow(5) { 28 29 @Override 30 public TraficLamp nextLamp() { 31 // TODO Auto-generated method stub 32 return Red; 33 } 34 35 };//必須加分號 36 /* 37 * 若是寫下面的抽象方法,則必須讓子類實現該方法,也就是上面的三個元素。 38 */ 39 public abstract TraficLamp nextLamp(); 40 41 private int time; 42 43 private TraficLamp(int time) { 44 this.time = time; 45 } 46 } 47 48 public static void main(String[] args) { 49 TraficLamp m = TraficLamp.Red; 50 System.out.println(m); 51 System.out.println(m.name()); 52 System.out.println(m.ordinal()); 53 System.out.println(TraficLamp.valueOf("Red").toString());//是red的話CE 54 System.out.println(TraficLamp.values().length); 55 56 new Date(300) {//new子類的對象並調用父類的有參構造方法這樣是可以的 57 }; 58 } 59 //如果枚舉只有一個成員時就可以作為單例實現方式 60 }
26.編寫一個方法,返回一個double型二維數組,數組中的元素通過解析字符串獲得

1 package b; 2 3 /* 4 * 編寫一個方法,返回一個double型二維數組,數組中的元素通過解析 5 * 字符串貨的。如:參數列表"1,2;3,4,5;6,7,8" 6 */ 7 public class TestDouble { 8 public static void main(String[] args) { 9 double[][] d; 10 String s = "1,2;3,4,5;6,7,8"; 11 String[] sFirst = s.split(";"); 12 d = new double[sFirst.length][]; 13 for(int i=0; i<sFirst.length; i++) { 14 //System.out.println(sFirst[i]);////驗證分的對否 15 String[] sSecond = sFirst[i].split(","); 16 d[i] = new double[sSecond.length]; 17 for(int j=0; j<sSecond.length; j++) { 18 d[i][j] = Double.parseDouble(sSecond[j]); 19 } 20 21 } 22 for(int i=0; i<d.length; i++) { 23 for(int j=0; j<d[i].length; j++) { 24 System.out.print(d[i][j]+" "); 25 } 26 System.out.println(); 27 } 28 System.out.println("-----ok-------"); 29 } 30 }
27.Enhanced

1 package b; 2 3 import java.util.*; 4 /* 5 * Enhanced for循環是在jdk1.5后才有的, 6 * 與數組相比不能方便地訪問下標值, 7 * 與使用iterator的集合相比不能方便地刪除集合中的內容。 8 * 除了簡單遍歷並輸出內容外比建議使用此法。 9 */ 10 public class TestEnhancedFor { 11 public static void main(String[] args) { 12 int[] a = {1,3,5,6}; 13 for(int i : a) { 14 System.out.println(i); 15 } 16 17 Collection c = new ArrayList(); 18 c.add(new String("aaa")); 19 c.add(new String("bbb")); 20 c.add(new String("ccc")); 21 for(Object o : c) {//Object的第一個字母大寫 22 System.out.println(o);//調用Object的toString方法, 23 //而在String里又重寫了toString方法,所以實際上調用的是String里的 24 } 25 } 26 }
28.Applet

1 package b; 2 3 import java.applet.Applet; 4 import java.awt. *; 5 6 public class TestApplet extends Applet 7 { 8 public void paint(Graphics gr) 9 { 10 setBackground ( Color.pink); 11 gr.drawString (" 黃鶴樓 ", 25, 30); 12 gr.drawString ("昔人已乘黃鶴去, 此地空余黃鶴樓。", 25, 50) ; 13 gr.drawString ("黃鶴一去不復返, 白雲千載空悠悠。", 25, 70) ; 14 gr.drawString ("晴川歷歷漢陽樹, 芳草萋萋鸚鵡洲。", 25, 90) ; 15 gr.drawString ("日暮鄉關何處是, 煙波江上使人愁。", 25, 110) ; 16 gr.drawString ("---崔顥", 50, 150) ; 17 } 18 }
29.三種方法統計字母個數

1 package b; 2 /* 3 * 統計字符串里大小寫字母和非字母的個數 4 */ 5 public class Statistics { 6 public static void main(String[] args) { 7 String str = "jkhshfs44__sjjkssfj jksn"; 8 int lowNum = 0,upperNum = 0,notNum = 0; 9 System.out.println("第一種方法"); 10 for(int i=0; i<str.length(); i++) { 11 char ch = str.charAt(i); 12 if(ch>='a'&&ch<='z') { 13 lowNum++; 14 }else if(ch>='A'&&ch<='Z') { 15 upperNum++; 16 }else { 17 notNum++;//變量未初始化的話也會報錯 18 } 19 } 20 System.out.println("lowNum:"+lowNum+"upperNum:"+upperNum+"notNum:" + notNum); 21 System.out.println("第二種方法"); 22 lowNum = 0;upperNum = 0;notNum = 0; 23 for(int i=0; i<str.length(); i++) { 24 char ch = str.charAt(i); 25 String s1 = "abcdefghijklmnopqrstuvwxyz"; 26 String s2 = s1.toUpperCase(); 27 if(s1.indexOf(ch)!=-1) {//參數為int型但是字符類型是按ASCII碼的 28 lowNum++; 29 }else if(s2.indexOf(ch)!=-1) { 30 upperNum++; 31 }else { 32 notNum++; 33 } 34 } 35 System.out.println("lowNum:"+lowNum+"upperNum:"+upperNum+"notNum:" + notNum); 36 System.out.println("第三種方法"); 37 lowNum = 0;upperNum = 0;notNum = 0; 38 for(int i=0; i<str.length(); i++) { 39 char ch = str.charAt(i); 40 if(Character.isLowerCase(ch)) {//參數為int型但是字符類型是按ASCII碼的 41 lowNum++; 42 }else if(Character.isUpperCase(ch)) { 43 upperNum++; 44 }else { 45 notNum++; 46 } 47 } 48 System.out.println("lowNum:"+lowNum+"upperNum:"+upperNum+"notNum:" + notNum); 49 System.out.println("------ok-----------"); 50 } 51 52 } 53 /* 54 * 由於每次方法都需要重新初始化,只能“lowNum = 0;upperNum = 0;notNum = 0;”不能 55 * lowNum = 0,upperNum = 0,notNum = 0; 56 */
30.遞歸展示文件結構

1 package b; 2 3 import java.io.File; 4 /* 5 * 以樹狀形式展現所有的目錄。子目錄以及文件, 6 * 實際就是遞歸輸出目錄結構 7 */ 8 public class ShowDirectory { 9 public static void main(String[] args) { 10 File f = new File("e:/A");//這個是確實先在磁盤上建立好的 11 System.out.println(f.getName()); 12 list(f,1);//從1開始是因為A父目錄要和下一個區分開 13 System.out.println("--------ok--------"); 14 } 15 private static void list(File f,int depth){ 16 /*第二個參數是為了凸顯層次結構,每遞歸深入一次就縮進一次 17 depth定義為成員變量的話,沒上一次就減一,下一次就加一,很麻煩 18 */ 19 String str = ""; 20 for(int i=0; i<depth; i++) { 21 str += " "; 22 } 23 File[] childs = f.listFiles(); 24 for(int i=0; i<childs.length; i++) { 25 System.out.println(str + childs[i].getName()); 26 if(childs[i].isDirectory()) { 27 list(childs[i],depth+1); 28 } 29 } 30 } 31 }
31.Generic

1 package b; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 import java.util.HashSet; 6 import java.util.List; 7 import java.util.Iterator;; 8 /* 9 * 泛型(generic):C/C++里也有泛型 10 * (java的泛型底層實現比較麻煩),一般和 11 * 自動打包解包一起用,以前裝入的東西都 12 * 作為Object還需要強轉從而在編譯時找不到錯誤, 13 * 定義時就限制里面可以裝入的對象類型, 14 * 也可以在Collection和Iterator里指定, 15 * 什么時間才可以使用泛型呢,查看API文檔, 16 * 只要后面有尖括號,那么就可以,程序的可讀性就增強了,隨之健壯性也增強啦。 17 */ 18 public class TestGeneric { 19 public static void main(String[] args) { 20 List<String > ls = new ArrayList<String>(); 21 ls.add("aaa"); 22 ls.add("bbb"); 23 ls.add("ccc"); 24 ls.add("ddd"); 25 for(int i=0; i<ls.size(); i++) { 26 String s = ls.get(i);//不需要強轉了 27 System.out.println(s); 28 } 29 30 Collection <String> str = new HashSet<String>(); 31 str.add("aaa"); 32 str.add("bbb"); 33 str.add("ccc"); 34 str.add("ddd"); 35 for(Iterator<String> ptr = str.iterator(); ptr.hasNext();) { 36 String s = ptr.next(); 37 System.out.println(s); 38 } 39 } 40 } 41 42 class Another implements Comparable<Another> { 43 int age; 44 45 public int compareTo(Another other) { 46 if(this.age>other.age) { 47 return 1; 48 }else if(this.age == other.age) { 49 return 0; 50 }else { 51 return -1; 52 } 53 } 54 55 }
32.Comparable接口

1 package b; 2 3 import java.util.Collections; 4 import java.util.LinkedList; 5 import java.util.List; 6 7 public class TestComparable { 8 public static void main(String[] args) { 9 List a = new LinkedList(); 10 a.add(new AnotherName("a", "b")); 11 a.add(new AnotherName("a", "d")); 12 a.add(new AnotherName("c", "b")); 13 Collections.sort(a);//重寫了compareTo方法 14 for(Object i : a) {//前面寫成AnotherName就CE 15 AnotherName b = (AnotherName)i; 16 System.out.println(b); 17 } 18 System.out.println("----------ok----------"); 19 } 20 } 21 22 //原來忘了實現這個Comparable接口,一直提示ClassCastEXception 23 class AnotherName implements Comparable { 24 private String firstName,lastName; 25 public AnotherName(String firstName,String lastName) { 26 this.firstName = firstName; 27 this.lastName = lastName; 28 } 29 public String getFirstName() { 30 return firstName; 31 } 32 public void setFirstName(String firstName) { 33 this.firstName = firstName; 34 } 35 public String getLastName() { 36 return lastName; 37 } 38 public void setLastName(String lastName) { 39 this.lastName = lastName; 40 } 41 42 //小馬說的,這是最簡單的 43 public int hashCode() { 44 return firstName.hashCode(); 45 } 46 public boolean equals(Object obj) { 47 if(obj instanceof AnotherName) { 48 AnotherName other = (AnotherName)obj; 49 return firstName.equals(other.firstName) 50 && lastName.equals(other.lastName); 51 } 52 return super.equals(obj); 53 } 54 //也是小馬寫的,先比較姓氏也就是lastName 55 public int compareTo(Object o) {//最后一個o是小寫,重寫必copy 56 AnotherName other = (AnotherName)o; 57 int intCmp = lastName.compareTo(other.lastName); 58 if(intCmp==0) { 59 return firstName.compareTo(other.firstName); 60 }else { 61 return intCmp; 62 } 63 } 64 public String toString() { 65 return firstName + " " + lastName; 66 } 67 }
33.正則表達式做EmailSpider

1 package b; 2 3 import java.io.BufferedReader; 4 import java.io.FileNotFoundException; 5 import java.io.FileReader; 6 import java.io.IOException; 7 import java.util.regex.Matcher; 8 import java.util.regex.Pattern; 9 10 /* 11 * 需要什么樣的方法的話先些方法名 12 * 然后ctrl + 1列出推薦,系統創建該方法 13 */ 14 public class EmailSpider { 15 16 public static void main(String[] args) { 17 try { 18 BufferedReader br = new BufferedReader(new FileReader("F:\\regex.html")); 19 String line = ""; 20 21 try { 22 while((line=br.readLine())!=null) { 23 solve(line); 24 } 25 } catch (IOException e) { 26 // TODO Auto-generated catch block 27 e.printStackTrace(); 28 } 29 } catch (FileNotFoundException e) { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 } 33 } 34 35 private static void solve(String line) { 36 //正則表達式要是不滿足相應功能的話不會出錯,因為他是字符串 37 Pattern p = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+"); 38 Matcher m = p.matcher(line); 39 40 while(m.find()) { 41 System.out.println(m.group()); 42 } 43 } 44 }