Java进阶代码

  本文重在温习……不过初学以及进阶高手不可错过

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 }
View Code

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 }
View Code

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 }
View Code

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 }
View Code

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 }
View Code

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
View Code

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 */
View Code

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 }
View Code

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 }
View Code

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 }
View Code

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  */
View Code

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 }
View Code

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 }
View Code

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 }
View Code

 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 }
View Code

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 }
View Code

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 }
View Code

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 }
View Code

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 }
View Code

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  */
View Code

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 }
View Code

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 }
View Code

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 }
View Code
 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 }
View Code

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 }
View Code

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 }
View Code

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 }
View Code

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 }
View Code

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 }
View Code

 Java进阶代码

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  */
View Code

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 }
View Code

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 }
View Code

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 }
View Code

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 }
View Code

你可能感兴趣的:(java)