Java进阶代码的具体写法

简介: Java进阶代码的具体写法
  1. public static void arraycopy(全小写)(object src,int srcPos,object dest,int destPos,int length)

复制代码
View Code
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; ia[mid]) {
28 start = mid +1;
29 }else {
30 end = mid -1;
32 mid = (start + end)/2;
33 }
34 return -1;
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.统计代码里多少空行,注释行,程序行
3 /

4 统计代码里多少空行,注释行,程序行
5
实际上使用String里的startsWith和endsWith也行.
6 若是项目经理用的话还要统计每行的字符数是否以{;结尾,防止偷懒
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 {
16 static long normalLines = 0;
17 static long commentLines = 0;
18 static long whiteLines = 0;
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.面向对象思路解决约瑟夫问题
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; iyear)
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
3 import java.util.HashMap;
4 import java.util.Map;
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 }
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.事件监听
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();
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();
34 //显示窗体
35 f.setVisible(true);
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 });
58
59 public static void main(String[] agrs)
60 {
61 new FrameDemo();
62 }
63 }
13.split
4
判断一个正整数是几位数在while循环里不断除以10,直到商为0
5 或者转换为字符串只需求出长度即可。
6
/
7 public class TestSplit {
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--------");

  1. 多维数组
    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 {
    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 = new HashSet();//若是import java.util.Set就CE
    12 s.add("hello");
    13 s.add(new OtherName("f1","f2"));
    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();
    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.内部类
    3 public abstract class Week {
    4 private Week(){
    5
    6 }
    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 };//必须加分号
    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 }
    28 };
    29
    30 public abstract Week nextDay();//必须加上abstract,否则总提示需要返回值
    31
    32 //抽象类中可以有非抽象方法,子类实现该类的时候可以不重写该方法
    33 public String toString() {
    34 return this==sun?"Sunday":"Monday";
    36
    19.Map
    5 import java.util.TreeMap;
    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));
    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类
    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); 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
    3 基本数据类型包装类(包装成对象分配在堆内存):在java.lang包,
    4
    里面都有MAX_VALUE,MIN_VALUE,和SIZE,
    5 用于各种数之间的转换,查看API。
    7 public class TestInteger {
    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
    rr;
    21 try {
    22 int k = Integer.parseInt("1.25");
    23 k += 1;
    24 }catch (NumberFormatException e) {
    25 System.out.println("数据格式不对");
    26 //e.printStackTrace();
    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 }
    35 }
    22.iterator
    6
    Collections是类,包含shuffle,sort,binarySearch
    8 public class TestIterator {
    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-------");
    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;
    55 public void setLastName(String lastName) {
    56 this.lastName = lastName;
    59 //小马说的,这是最简单的
    60 public int hashCode() {
    61 return firstName.hashCode();
    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
    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 }
    3 import java.util.ArrayList;
    4 import java.util.Collection;
    5 import java.util.HashSet;
    7 public class Reflect {
    8
    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);
    21 coll.add(p1);
    22 coll.add(p2);
    23 coll.add(p3);
    24 coll.add(p4);
    25 coll.add(p4);
    26 /

    27 参与hashCode运算的值,在加载后就不应该再改动,否则删除的话是删不掉的(不会报错),这就是内存泄露
    29 System.out.println(coll.size());
    31 }
    33 class Pointer {
    34 public int x = 0;
    35 public int y = 0;
    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;
    67 }
    24.创建File
    3 import java.io.File;
    4 import java.io.IOException;
    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.枚举+内部类实现交通灯
    3 import java.util.Date;
    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 },//必须加逗号
    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) {
    29 @Override
    30 public TraficLamp nextLamp() {
    31 // TODO Auto-generated method stub
    32 return Red;
    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 }
    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型二维数组,数组中的元素通过解析字符串获得
    4 编写一个方法,返回一个double型二维数组,数组中的元素通过解析
    5
    字符串货的。如:参数列表"1,2;3,4,5;6,7,8"
    7 public class TestDouble {
    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]);
    20
    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();
    28 System.out.println("-----ok-------");
    29 }
    30 }
    27.Enhanced
    4 /
    5
    Enhanced for循环是在jdk1.5后才有的,
    6 与数组相比不能方便地访问下标值,
    7
    与使用iterator的集合相比不能方便地删除集合中的内容。
    8 除了简单遍历并输出内容外比建议使用此法。
    10 public class TestEnhancedFor {
    12 int[] a = {1,3,5,6};
    13 for(int i : a) {
    14 System.out.println(i);
    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
    3 import java.applet.Applet;
    4 import java.awt.
    ;
    6 public class TestApplet extends Applet
    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.三种方法统计字母个数
3 统计字符串里大小写字母和非字母的个数
4
/
5 public class Statistics {
7 String str = "jkhshfs44__sjjkssfj jksn";
8 int lowNum = 0,upperNum = 0,notNum = 0;
9 System.out.println("第一种方法");
10 for(int i=0; i='a'&&ch<='z') {
13 lowNum++;
14 }else if(ch>='A'&&ch<='Z') {
15 upperNum++;
17 notNum++;//变量未初始化的话也会报错
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 ls = new ArrayList();
21 ls.add("aaa");
22 ls.add("bbb");
23 ls.add("ccc");
24 ls.add("ddd");
25 for(int i=0; i str = new HashSet();
31 str.add("aaa");
32 str.add("bbb");
33 str.add("ccc");
34 str.add("ddd");
35 for(Iterator ptr = str.iterator(); ptr.hasNext();) {
36 String s = ptr.next();
37 System.out.println(s);
38 }
39 }
40 }
41
42 class Another implements Comparable {
43 int age;
44
45 public int compareTo(Another other) {
46 if(this.age>other.age) {
48 }else if(this.age == other.age) {
49 return 0;
50 }else {
51 return -1;
52 }
53 }
54
55 }
32.Comparable接口
3 import java.util.Collections;
4 import java.util.LinkedList;
5 import java.util.List;
7 public class TestComparable {
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);
18 System.out.println("----------ok----------");
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;
32 public void setFirstName(String firstName) {
33 this.firstName = firstName;
35 public String getLastName() {
36 return lastName;
37 }
38 public void setLastName(String lastName) {
41 //代码效果参考:http://0791zd.com/bx/art_4173.html

42 //小马说的,这是最简单的
43 public int hashCode() {
44 return firstName.hashCode();
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);
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;
33.正则表达式做EmailSpider
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;
10 /*
//代码效果参考:http://0791zd.com/bx/art_6283.html

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 = "";
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();

//代码效果参考:http://0791zd.com/zx/art_5248.html
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 }

相关文章
|
15天前
|
设计模式 Java
Java设计模式:组合模式的介绍及代码演示
组合模式是一种结构型设计模式,用于将多个对象组织成树形结构,并统一处理所有对象。例如,统计公司总人数时,可先统计各部门人数再求和。该模式包括一个通用接口、表示节点的类及其实现类。通过树形结构和节点的通用方法,组合模式使程序更易扩展和维护。
Java设计模式:组合模式的介绍及代码演示
|
4天前
|
Java
java小工具util系列4:基础工具代码(Msg、PageResult、Response、常量、枚举)
java小工具util系列4:基础工具代码(Msg、PageResult、Response、常量、枚举)
16 5
|
6天前
|
Java API 开发者
探索Java中的Lambda表达式:简洁与强大的代码实践
本文深入探讨Java中Lambda表达式的定义、用法及优势,通过实例展示其如何简化代码、提升可读性,并强调在使用中需注意的兼容性和效率问题。Lambda作为Java 8的亮点功能,不仅优化了集合操作,还促进了函数式编程范式的应用,为开发者提供了更灵活的编码方式。
|
2天前
|
Java 开发者
探索Java中的Lambda表达式:简化你的代码之旅##
【8月更文挑战第62天】 Java 8的发布为开发者带来了诸多新特性,其中最引人注目的无疑是Lambda表达式。这一特性不仅让代码变得更加简洁,还极大地提升了开发的效率。本文将通过实际示例,展示如何利用Lambda表达式来优化我们的代码结构,同时探讨其背后的工作原理和性能考量。 ##
|
6天前
|
Java API 开发者
探索Java中的Lambda表达式:简化代码,提升效率
【9月更文挑战第27天】在Java 8中引入的Lambda表达式为编程带来了革命性的变化。通过简洁的语法和强大的功能,它不仅简化了代码编写过程,还显著提升了程序的执行效率。本文将深入探讨Lambda表达式的本质、用法和优势,并结合实例演示其在实际开发中的应用。无论你是Java新手还是资深开发者,都能从中获得启发,优化你的代码设计。
|
6天前
|
Java Linux Python
Linux环境下 代码java调用python出错
Linux环境下 代码java调用python出错
19 3
|
6天前
|
存储 Java 索引
使用java代码实现左右括号查找
使用java代码实现左右括号查找
|
7天前
|
算法 Java
java 概率抽奖代码实现
java 概率抽奖代码实现
|
15天前
|
Java 程序员 API
Java中的Lambda表达式:简化代码的秘密武器
在Java 8中引入的Lambda表达式是一种强大的编程工具,它可以显著简化代码,提高可读性。本文将介绍Lambda表达式的基本概念、优势以及在实际开发中的应用。通过具体示例,您将了解如何使用Lambda表达式来简化集合操作、线程编程和函数式编程。让我们一起探索这一革命性的特性,看看它是如何改变Java编程方式的。
23 4
|
15天前
|
Java 开发者
探索Java中的Lambda表达式:简化你的代码
【8月更文挑战第49天】在Java 8的发布中,Lambda表达式无疑是最令人兴奋的新特性之一。它不仅为Java开发者提供了一种更加简洁、灵活的编程方式,而且还极大地提高了代码的可读性和开发效率。本文将通过实际代码示例,展示如何利用Lambda表达式优化和重构Java代码,让你的编程之旅更加轻松愉快。
下一篇
无影云桌面